This question already has an answer here:
- Use 'import module' or 'from module import'? 13 answers
I'm wondering if there's any difference between the code fragment
from urllib import request
and the fragment
import urllib.request
or if they are interchangeable. If they are interchangeable, which is the "standard"/"preferred" syntax (if there is one)?
Thanks!
It depends on how you want to access the import when you refer to it.
You can also alias things yourself when you import for simplicity or to avoid masking built ins:
In python 2.x at least you cannot do
import urllib2.urlopen
You have to do
from urllib2 import urlopen
There is a difference. In some cases, one of those will work and the other won't. Here is an example: say we have the following structure:
Now, I want to import
b.py
intoa.py
. And I want to importa.py
tofoo
. How do I do this? Two statements, ina
I write:In
foo.py
I write:Well, this will generate an
ImportError
when trying to runfoo.py
. The interpreter will complain about the import statement ina.py
(import b
) saying there is no module b. So how can one fix this? In such a situation, changing the import statement ina
toimport mylib.b
will not work sincea
andb
are both inmylib
. The solution here (or at least one solution) is to use absolute import:Source: Python: importing a module that imports a module
Many people have already explained about
import
vsfrom
, so I want to try to explain a bit more under the hood, where the actual difference lies.First of all, let me explain exactly what the basic import statements do.
import X
from X import *
Now let's see what happens when we do
import X.Y
:Check
sys.modules
with nameos
andos.path
:Check
globals()
andlocals()
namespace dict with nameos
andos.path
:From the above example, we found that only
os
is added to the local and global namespaces. So, we should be able to useos
:…but not
path
:Once you delete the
os
fromlocals()
namespace, you won't be able to access eitheros
oros.path
, even though they do exist insys.modules
:Now let's look at
from
.from
Check
sys.modules
with nameos
andos.path
:So
sys.modules
looks the same as it did when we imported usingimport name
.Okay. Let's check what it the
locals()
andglobals()
namespace dicts look like:You can access by using
path
, but not byos.path
:Let's delete 'path' from locals():
One final example using aliasing:
And no path defined:
One pitfall about using
from
When you are import same
name
from two different modules:Import stat from
shutil
again:THE LAST IMPORT WILL WIN
My main complaint with import urllib.request is that you can still reference urllib.parse even though it isn't imported.
Also request for me is under urllib3. Python 2.7.4 ubuntu
There's very little difference in functionality, but the first form is preferential, as you can do
where in the second form that would have to be
and you'd have to reference using the fully qualified name, which is way less elegant.