When attempting to import
from an alias - which is common in scala
I was surprised to see the following results:
Create an alias
import numpy as np
Use the alias to import modules it contains
from np import linalg
ImportError: No module named np.linalg
Is there any other syntax/equivalent in python useful for importing modules?
Import aliases are where you take your standard import, but instead of using a pre-defined name by the exporting module, you use a name that is defined in the importing module.
If multiple modules imports the same module then angular evaluates it only once (When it encounters the module first time). It follows this condition even the module appears at any level in a hierarchy of imported NgModules.
In Python, you use the import keyword to make code in one module available in another. Imports in Python are important for structuring your code effectively. Using imports properly will make you more productive, allowing you to reuse code while keeping your projects maintainable.
First, default imports are nameless. Or rather : it looses its name during exportation. Be it variables, constants, objects, classes, etc : they all have a name in their module. They are exported as default and it becomes their new name sort of. So when we write : import detectRotation from 'rotate'
Using import module as name
does not create an alias. You misunderstood the import system.
Importing does two things:
sys.modules
. This is done once only; subsequent imports re-use the already loaded module object.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With