Should I use
from foo import bar
OR
import foo.bar as bar
when importing a module and there is no need/wish for changing the name (bar
)?
Are there any differences? Does it matter?
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
<module 'posixpath' from '/Users/mj/Development/venvs/stackoverflow-2.7/lib/python2.7/posixpath.pyc'>
>>> from os import path
>>> path
<module 'posixpath' from '/Users/mj/Development/venvs/stackoverflow-2.7/lib/python2.7/posixpath.pyc'>
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 "<stdin>", line 1, in <module>
ImportError: No module named walk
Note that if bar
is both a module inside foo
and an object in the foo
package namespace (so imported into the __init__.py
module or defined there), then from foo import bar
will import the object, and import foo.bar as bar
imports the module.
* 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.