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?
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?
The only thing I can see for the second option is that you will need as many lines as things you want to import. For example :
Instead of simply doing :
You can use as to rename modules suppose you have two apps that have views and you want to import them
if you want multiple import use comma separation
This is a late answer, arising from what is the difference between 'import a.b as b' and 'from a import b' in python
This question has been flagged as a duplicate, but there is an important difference between the two mechanisms that has not been addressed by others.
from foo import bar
imports any object calledbar
from namespacefoo
into the current namespace.import foo.bar as bar
imports an importable object (package/module/namespace) calledfoo.bar
and gives it the aliasbar
.What's the difference?
Take a directory (package) called
foo
which has an__init__.py
containing:Meanwhile, there is also a module in
foo
calledbar.py
.Gives:
Whereas:
Gives:
So it can be seen that
import foo.bar as bar
is safer.Assuming that
bar
is a module or package infoo
, there is no difference, it doesn't matter. The two statements have exactly the same result:If
bar
is not a module or package, the second form will not work; a traceback is thrown instead: