Import modules using an alias
Using import module as name
does not create an alias. You misunderstood the import system.
Importing does two things:
- Load the module into memory and store the result in
sys.modules
. This is done once only; subsequent imports re-use the already loaded module object. - Bind one or more names in your current namespace.
The as name
syntax lets you control the name in the last step.
For the from module import name
syntax, you need to still name the full module, as module
is looked up in sys.modules
. If you really want to have an alias for this, you would have to add extra references there:
import numpy # loads sys.modules['numpy']
import sys
sys.modules['np'] = numpy # creates another reference
However, doing so can have side effects when you also are importing submodules. Generally speaking, you don't want to create aliases for packages by poking about in sys.modules
without also creating aliases for all (possible) submodules as not doing so can cause Python to re-import submodules as separate namespaces.
In this specific case, importing numpy
also triggers the loading of numpy.linalg
, so all you really have to do is:
import numpy as np
# np.linalg now is available
No module aliasing is needed. For packages that don't import submodules automatically, you'd have to use:
import package as alias
import package.submodule
and alias.submodule
is then available anyway, because a submodule is always added as an attribute on the parent package.
My understanding of your example would be that since you already imported numpy, you couldn't re import it with an alias, as it would already have the linalg portion imported.