Import modules using an alias [duplicate]

核能气质少年 提交于 2019-11-28 10:29:41

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.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!