Why can't I import array from np after setting

2019-02-28 17:22发布

问题:

To make it more clear:

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.