from … import OR import … as for modules

后端 未结 6 476
萌比男神i
萌比男神i 2020-11-29 02:57

Should I use

from foo import bar

OR

import foo.bar as bar

when importing a module and an

6条回答
  •  余生分开走
    2020-11-29 03:21

    Assuming that bar is a module or package in foo, there is no difference*, it doesn't matter. The two statements have exactly the same result:

    >>> import os.path as path
    >>> path
    
    >>> from os import path
    >>> path
    
    

    If bar is not a module or package, the second form will not work; a traceback is thrown instead:

    >>> import os.walk as walk
    Traceback (most recent call last):
      File "", line 1, in 
    ImportError: No module named walk
    

    * In Python 3.6 and before, there was a bug with the initialization ordering of packages containing other modules, where in the loading stage of the package using import contained.module.something as alias in a submodule would fail where from contained.module import something as alias would not. See Imports in __init__.py and `import as` statement for a very illustrative example of that problem, as well as Python issues #23203 and #30024.

提交回复
热议问题