It depends on how you want to access the import when you refer to it.
from urllib import request
# access request directly.
mine = request()
import urllib.request
# used as urllib.request
mine = urllib.request()
You can also alias things yourself when you import for simplicity or to avoid masking built ins:
from os import open as open_
# lets you use os.open without destroying the
# built in open() which returns file handles.
Answer from g.d.d.c on Stack OverflowIt depends on how you want to access the import when you refer to it.
from urllib import request
# access request directly.
mine = request()
import urllib.request
# used as urllib.request
mine = urllib.request()
You can also alias things yourself when you import for simplicity or to avoid masking built ins:
from os import open as open_
# lets you use os.open without destroying the
# built in open() which returns file handles.
Many people have already explained about import vs from, 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
Imports the module
X, 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.:X.nameorX.attribute)
from X import *
Imports the module
X, and creates references to all public objects defined by that module in the current namespace (that is, everything that doesn’t have a name starting with_) or whatever name you mentioned.Or, in other words, after you've run this statement, you can simply use a plain (unqualified) name to refer to things defined in module
X. ButXitself is not defined, soX.namedoesn't work. And ifnamewas already defined, it is replaced by the new version. And if name inXis changed to point to some other object, your module won’t notice.This makes all names from the module available in the local namespace.
Now let's see what happens when we do import X.Y:
>>> import sys
>>> import os.path
Check sys.modules with name os and os.path:
>>> sys.modules['os']
<module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
>>> sys.modules['os.path']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
Check globals() and locals() namespace dict with name os and os.path:
>>> globals()['os']
<module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
>>> locals()['os']
<module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
>>> globals()['os.path']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'os.path'
>>>
From the above example, we found that only os is added to the local and global namespaces.
So, we should be able to use os:
>>> os
<module 'os' from
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
>>> os.path
<module 'posixpath' from
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>>
…but not path:
>>> path
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'path' is not defined
>>>
Once you delete the os from locals() namespace, you won't be able to access either os or os.path, even though they do exist in sys.modules:
>>> del locals()['os']
>>> os
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'os' is not defined
>>> os.path
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'os' is not defined
>>>
Now let's look at from.
from
>>> import sys
>>> from os import path
Check sys.modules with name os and os.path:
>>> sys.modules['os']
<module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
>>> sys.modules['os.path']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
So sys.modules looks the same as it did when we imported using import name.
Okay. Let's check what it the locals() and globals() namespace dicts look like:
>>> globals()['path']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>> locals()['path']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>> globals()['os']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'os'
>>>
You can access by using path, but not by os.path:
>>> path
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>> os.path
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'os' is not defined
>>>
Let's delete 'path' from locals():
>>> del locals()['path']
>>> path
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'path' is not defined
>>>
One final example using aliasing:
>>> from os import path as HELL_BOY
>>> locals()['HELL_BOY']
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>> globals()['HELL_BOY']
<module 'posixpath' from /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>>
And no path defined:
>>> globals()['path']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'path'
>>>
One pitfall about using from
When you import the same name from two different modules:
>>> import sys
>>> from os import stat
>>> locals()['stat']
<built-in function stat>
>>>
>>> stat
<built-in function stat>
Import stat from shutil again:
>>>
>>> from shutil import stat
>>> locals()['stat']
<module 'stat' from
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/stat.pyc'>
>>> stat
<module 'stat' from
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/stat.pyc'>
>>>
THE LAST IMPORT WILL WIN
What does a Python import statement actually do?
python - 'import module' vs. 'from module import function' - Software Engineering Stack Exchange
When/why should i use "from module import *" instead of "import module" ?
python - Use 'import module' or 'from module import'? - Stack Overflow
I mean, I know it lets you use functions from that library, but how does it do this?
Like, in C/C++, I know a #include statement essentially tells the preprocessor to paste the contents of the .h file into the file with the #include statement, and then the linker matches the function declarations to their definitions in the relevant .c files.
Does something similar happen with import statements in Python? Or is it a totally different process, since Python is normally interpreted, not compiled? I would think it's at least sort of similar, since a lot of Python libraries are written in C to begin with.
Importing the module doesn't waste anything; the module is always fully imported (into the sys.modules mapping), so whether you use import sys or from sys import argv makes no odds.
The only difference between the two statements is what name is bound; import sys binds the name sys to the module (so sys -> sys.modules['sys']), while from sys import argv binds a different name, argv, pointing straight at the attribute contained inside of the module (so argv -> sys.modules['sys'].argv). The rest of the sys module is still there, whether you use anything else from the module or not.
There is also no performance difference between the two approaches. Yes, sys.argv has to look up two things; it has to look up sys in your global namespace (finds the module), then look up the attribute argv. And yes, by using from sys import argv you can skip the attribute lookup, since you already have a direct reference to the attribute. But the import statement still has to do that work, it looks up the same attribute when importing, and you'll only ever need to use argv once. If you had to use argv thousands of times in a loop, it could perhaps make a difference, but in this specific case it really does not.
Hence, the choice between one or the other should be based solely on coding style.
In a large module, I'd certainly use import sys; code documentation matters, and using sys.argv somewhere in a large module makes it much clearer what you are referring to than just argv ever would.
If the only place you use argv is in a '__main__' block to call a main() function, by all means use from sys import argv if you feel happier about that:
if __name__ == '__main__':
from sys import argv
main(argv)
I'd still use import sys there myself. All things being equal (and they are, exactly, in terms of performance and number of characters used to write it), that is just easier on the eye for me.
If you are importing something else altogether, then perhaps performance comes into play. But only if you use a specific name in a module many times over, in a critical loop for example. But then creating a local name (within a function) is going to be faster still:
import somemodule
def somefunction():
localname = somemodule.somefunctionorother
while test:
# huge, critical loop
foo = localname(bar)
There are two reasons in favor of using import module rather than from module import function.
First is the namespace. Importing a function into the global namespace risks name collisions.
Second isn't that relevant to standard modules, but significant for you own modules, especially during development. It's the option to reload() a module. Consider this:
from module import func
...
reload(module)
# func still points to the old code
On the other hand
import module
...
reload(module)
# module.func points to the new code
As for speed...
we are importing only the function that is needed rather than import the whole module (which contains more useless functions which python will waste time importing them)
Whether you import a module or import a function from a module, Python will parse the whole module. Either way the module is imported. "Importing a function" is nothing more than binding the function to a name. In fact import module is less work for interpreter than from module import func.
Even after reading about it, i'm still a bit confused about with which method i should use. For example i wanted to use this guy's great module to have the logging module output to a file and the console at the same time.
But i tried using this it will return an error: NameError: name 'initialize_logger' is not defined
import loggerinitializer
And this will not and will work just fine:
from loggerinitializer import *
So i suppose there is something i still don't get about import, could someone help me ?
EDIT: added which of the 2 didn't work
The difference between import module and from module import foo is mainly subjective. Pick the one you like best and be consistent in your use of it. Here are some points to help you decide.
import module
- Pros:
- Less maintenance of your
importstatements. Don't need to add any additional imports to start using another item from the module
- Less maintenance of your
- Cons:
- Typing
module.fooin your code can be tedious and redundant (tedium can be minimized by usingimport module as mothen typingmo.foo)
- Typing
from module import foo
- Pros:
- Less typing to use
foo - More control over which items of a module can be accessed
- Less typing to use
- Cons:
- To use a new item from the module you have to update your
importstatement - You lose context about
foo. For example, it's less clear whatceil()does compared tomath.ceil()
- To use a new item from the module you have to update your
Either method is acceptable, but don't use from module import *.
For any reasonable large set of code, if you import * you will likely be cementing it into the module, unable to be removed. This is because it is difficult to determine what items used in the code are coming from 'module', making it easy to get to the point where you think you don't use the import any more but it's extremely difficult to be sure.
There's another detail here, not mentioned, related to writing to a module. Granted this may not be very common, but I've needed it from time to time.
Due to the way references and name binding works in Python, if you want to update some symbol in a module, say foo.bar, from outside that module, and have other importing code "see" that change, you have to import foo a certain way. For example:
module foo:
bar = "apples"
module a:
import foo
foo.bar = "oranges" # update bar inside foo module object
module b:
import foo
print foo.bar # if executed after a's "foo.bar" assignment, will print "oranges"
However, if you import symbol names instead of module names, this will not work.
For example, if I do this in module a:
from foo import bar
bar = "oranges"
No code outside of a will see bar as "oranges" because my setting of bar merely affected the name "bar" inside module a, it did not "reach into" the foo module object and update its bar.
Isn't "from x import *" importing all definitions ? Aren't they same thing ?