Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

from ... import OR import ... as for modules

Should I use

from foo import bar 

OR

import foo.bar as bar 

when importing a module and and there is no need/wish for changing the name (bar)?

Are there any differences? Does it matter?

like image 940
embert Avatar asked Mar 07 '14 09:03

embert


People also ask

What is import as in Python?

In Python, you use the import keyword to make code in one module available in another. Imports in Python are important for structuring your code effectively. Using imports properly will make you more productive, allowing you to reuse code while keeping your projects maintainable.

What does from module import * mean in Python?

It just means that you import all(methods, variables,...) in a way so you don't need to prefix them when using them.

How can modules be imported?

Python import statement We can import a module using the import statement and access the definitions inside it using the dot operator as described above.

How do I import a function from a module?

You need to use the import keyword along with the desired module name. When interpreter comes across an import statement, it imports the module to your current program. You can use the functions inside a module by using a dot(.) operator along with the module name.


1 Answers

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 

* 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.

like image 135
Martijn Pieters Avatar answered Sep 19 '22 17:09

Martijn Pieters