The import as syntax was introduced in PEP 221 and is well documented there.
When importing a module through
import numpy
the numpy package is bound to the local numpy variable. The import as syntax just allows you to bind the import to the local variable name of your choice (usually to avoid name collisions, shorten the names of verbal modules, or standardize access to modules with compatible APIs).
Thus,
import numpy as np
equivalently
import numpy np = numpy del numpy
When trying to understand this mechanism, it is worth remembering that import numpy actually means import numpy as numpy .
When importing a submodule, you must refer to the name of the full parent module, since import mechanics occur at a higher level than the scope of the local variable. i.e.
import numpy as np import numpy.f2py
I also disagree with your statement that "where possible, [import numpy as np] should be." This is done for historical reasons, mainly because people get very tired of the prefix of each operation with numpy very quickly. It never stopped me from running into a name (laziness of programmers actually implies a higher chance of colliding with np )
Finally, to finish my exposé, here are 2 interesting uses of the import as mechanism that you should be aware of:
1. long subobjects
import scipy.ndimage.interpolation as warp warp.affine_transform(I, ...)
2. compatible APIs
try: import pyfftw.interfaces.numpy_fft as fft except: import numpy.fft as fft
hbristow
source share