Import modules using an alias [duplicate]

2019-01-27 08:04发布

问题:

This question already has an answer here:

  • Python: importing a sub‑package or sub‑module 3 answers

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?

回答1:

Using import module as name does not create an alias. You misunderstood the import system.

Importing does two things:

  1. 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.
  2. 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 can add extra references there:

import numpy  # loads sys.modules['numpy']
import sys

sys.modules['np'] = numpy  # creates another reference

Note that in this specific case, importing numpy also triggers the loading of numpy.linalg, so all you 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.



回答2:

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.



标签: python alias