I've tried to find a comprehensive guide on whether it is best to use import module
or from module import
? I've just started with Python and I'm trying to start off with best practices in mind.
Basically, I was hoping if anyone could share their experiences, what preferences other developers have and what's the best way to avoid any gotchas down the road?
Even though many people already explained about
import
vsimport from
, I want to try to explain a bit more about what happens under the hood, and where all the places it changes are.import foo
:Imports
foo
, and creates a reference to that module in the current namespace. Then you need to define completed module path to access a particular attribute or method from inside the module.E.g.
foo.bar
but notbar
from foo import bar
:Imports
foo
, and creates references to all the members listed (bar
). Does not set the variablefoo
.E.g.
bar
but notbaz
orfoo.baz
from foo import *
:Imports
foo
, and creates references to all public objects defined by that module in the current namespace (everything listed in__all__
if__all__
exists, otherwise everything that doesn't start with_
). Does not set the variablefoo
.E.g.
bar
andbaz
but not_qux
orfoo._qux
.Now let’s see when we do
import X.Y
:Check
sys.modules
with nameos
andos.path
:Check
globals()
andlocals()
namespace dicts withos
andos.path
:From the above example we found that only
os
is inserted in the local and global namespace. So, we should be able to use:But not
path
.Once you delete the
os
from locals() namespace, you won't be able to accessos
as well asos.path
even though they exist in sys.modules:Now let's talk about
import from
:from
:Check
sys.modules
withos
andos.path
:We found that in
sys.modules
we found as same as we did before by usingimport name
OK, let's check how it looks like in
locals()
andglobals()
namespace dicts:You can access by using name
path
not byos.path
:Let's delete 'path' from
locals()
:One final example using an alias:
And no path defined: