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

前端 未结 1 1004
生来不讨喜
生来不讨喜 2021-01-15 02:45

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: <

相关标签:
1条回答
  • 2021-01-15 03:19

    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.

    0 讨论(0)
提交回复
热议问题