Why is importing from a package invalid when the aliased name of package is used?

╄→尐↘猪︶ㄣ 提交于 2019-12-01 10:09:58

问题


To make it more clear, consider a numpy example :

import numpy as np
from numpy import array

This works as expected. But what about this:

from np import array

The output is:

Traceback (most recent call last)
  <ipython-input-21-d5c81fa93e5f> in <module>()
    ----> 1 from np import array
ModuleNotFoundError: No module named 'np'

Once I have set the alias of the imported module numpy as np, shouldn't I be able to import something else using np only?

Also, the id() of both is the same -- both numpy and np refer to the same thing.


回答1:


The module name is still numpy, even after you import the module as np.

What the import … as … syntax basically does is this:

np = internal_import_module('numpy')

So the np is just the local name that get used to refer to the numpy module. If you look at the module name of np, you can see that it’s still 'numpy':

>>> import numpy as np
>>> np.__name__
'numpy'

Now, the local name of a module is not being used at all when another import statement is being evaluated. So your from numpy import array is basically just this:

array = internal_import_module('numpy').array

Here array is again just a local name for the array member inside of the numpy module. It is however not a member inside of the np module because there simply isn’t a module with that name.



来源:https://stackoverflow.com/questions/51696602/why-is-importing-from-a-package-invalid-when-the-aliased-name-of-package-is-used

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