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 Overflow
🌐
Python documentation
docs.python.org › 3 › reference › import.html
5. The import system — Python 3.15.2 documentation
To begin the search, Python needs the fully qualified name of the module (or package, but for the purposes of this discussion, the difference is immaterial) being imported. This name may come from various arguments to the import statement, or from the parameters to the importlib.import_module() or __import__() functions.
Top answer
1 of 6
340

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.
2 of 6
275

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.name or X.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. But X itself is not defined, so X.name doesn't work. And if name was already defined, it is replaced by the new version. And if name in X is 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

Discussions

What does a Python import statement actually do?
It does work quite differently, though there are some similarities. Here, basically is how import works in the simple case (importing a pure python module that's not in a package). Python calls the special function __import__ This function first looks for the module in sys.modules which is basically a dictionary of module names to module objects. If it finds a module object proceed to step 8. If the module isn't in the cache, it uses the module resolution rules to find the file to import. if the file isn't found, error. If a .pyc bytecode file reqd and execute it If not open the file. Translate it to byte code, write this bytecode to a .pyc file and execute the byte code. Bind any top level variables, including functions and classes, to the module object. You can basically think of the module object as a big dictionary of variable name to value. If you did import foo, assign the module object to the variable foo (or whatever the module name is) If you did from foo import bar assign the value associated with the key bar to the variable bar. Do similarly if you use as to rename the import Put the module object in sys.modules if it isn't already there. A few key things to note: A module is automatically only imported once per program. Essentially 'include guards' are automatic. A module is run. That means top level statements in modules meant to be imported are dangerous. All modules have their own namespaces. There is no such thing as a Python variable outside of a namespace. Even 'global' variables are not truly global. All python files are modules. Unlike some languages, there is no distinction between a module and a script. More on reddit.com
🌐 r/learnprogramming
8
1
August 1, 2022
python - 'import module' vs. 'from module import function' - Software Engineering Stack Exchange
I always used this: from sys import argv and use argv with just argv. But there is this convention: import sys and using the argv by sys.argv The second method makes the code self documented. The... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
February 18, 2013
When/why should i use "from module import *" instead of "import module" ?
(Python 3.5.2 docs)[ https://docs.python.org/3/tutorial/modules.html] It's a namespace thing. When you use import module, you call it's functions/variables/etc. with module.function/attribute in the same way you would a different class: import math x = math.sin(math.sqrt(2)) class MyClass: def __init__(self, x): self.x = x foo = MyClass(4) print(foo.x) # 4 If you use from module import attr', it takes the nameattr' and brings it into the local namespace, so you don't need to call module.: from math import sqrt, sin x = sin(sqrt(2)) from module import * does this for every attribute (function/variable) in the module. from math import * x = sin(sqrt(2)) You can also use import ... as, which also defines a name. Say you had a module or attribute with a long name, like `This_Is_A_Long_Module_Namee". Rather than have to type that every time you need to reference it, you can do import This_Is_A_Long_Module_Name as longmod foo = longmod.bar() This works for methods as well: from foo import annoying_method_name as bar baz = bar() instead of import foo baz = foo.annoying_method_name() Edit - formatting More on reddit.com
🌐 r/learnpython
24
58
December 10, 2016
python - Use 'import module' or 'from module import'? - Stack Overflow
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. Bas... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Chris Yeh
chrisyeh96.github.io › 2017 › 08 › 08 › definitive-guide-python-imports.html
The Definitive Guide to Python import Statements | Chris Yeh
August 8, 2017 - The first time that a package or one of its modules is imported, Python will execute the __init__.py file in the root folder of the package if the file exists. All objects and functions defined in __init__.py are considered part of the package namespace. Consider the following example.
🌐
OpenClassrooms
openclassrooms.com › us › courses › 6900846-set-up-a-python-environment › 6989471-import-python-packages-and-modules
Import Python Packages and Modules - OpenClassrooms
While using from <package> import * in the Python shell is fine, it generally isn’t considered good practice in application source code.
🌐
W3Schools
w3schools.com › python › gloss_python_module_import_from.asp
Python Import From Module
Python Examples Python Compiler ... Study Plan Python Interview Q&A Python Training ... You can choose to import only parts from a module, by using the from keyword....
🌐
W3Schools
w3schools.com › python › python_modules.asp
Python Modules
You can choose to import only parts from a module, by using the from keyword.
Find elsewhere
🌐
Medium
s16h.medium.com › importing-star-in-python-88fe9e8bd4d2
Importing `*` in Python. This post discusses Python’s from… | by Shahriar Tajbakhsh | Medium
April 28, 2020 - What’s not mentioned above is what __all__ is. __all__ is a list of strings defining what symbols in a module (or a package as we’ll see later) will be exported when from <module> import * is used on the module. If we don’t define __all__ (we didn’t in something.py above), the default behaviour of import * is to import all names except those beginning with an underscore (_).
🌐
Reddit
reddit.com › r/learnprogramming › what does a python import statement actually do?
r/learnprogramming on Reddit: What does a Python import statement actually do?
August 1, 2022 -

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.

Top answer
1 of 3
3
It does work quite differently, though there are some similarities. Here, basically is how import works in the simple case (importing a pure python module that's not in a package). Python calls the special function __import__ This function first looks for the module in sys.modules which is basically a dictionary of module names to module objects. If it finds a module object proceed to step 8. If the module isn't in the cache, it uses the module resolution rules to find the file to import. if the file isn't found, error. If a .pyc bytecode file reqd and execute it If not open the file. Translate it to byte code, write this bytecode to a .pyc file and execute the byte code. Bind any top level variables, including functions and classes, to the module object. You can basically think of the module object as a big dictionary of variable name to value. If you did import foo, assign the module object to the variable foo (or whatever the module name is) If you did from foo import bar assign the value associated with the key bar to the variable bar. Do similarly if you use as to rename the import Put the module object in sys.modules if it isn't already there. A few key things to note: A module is automatically only imported once per program. Essentially 'include guards' are automatic. A module is run. That means top level statements in modules meant to be imported are dangerous. All modules have their own namespaces. There is no such thing as a Python variable outside of a namespace. Even 'global' variables are not truly global. All python files are modules. Unlike some languages, there is no distinction between a module and a script.
2 of 3
1
This is going to sound facetious, but it has to do with the answer to your question. Do you understand how python executes your file?
Top answer
1 of 9
275

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)
2 of 9
62

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.

🌐
Sentry
sentry.io › sentry answers › python › import files from a different folder in python
Python Import From Parent Directory and Subfolders | Sentry
Import modules from parent, child, and sibling directories using package relative imports with __init__.py or by adding paths to sys.path at runtime
🌐
Reddit
reddit.com › r/learnpython › when/why should i use "from module import *" instead of "import module" ?
r/learnpython on Reddit: When/why should i use "from module import *" instead of "import module" ?
December 10, 2016 -

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

🌐
DataCamp
datacamp.com › tutorial › modules-in-python
Python Modules Tutorial: Importing, Writing, and Using Them | DataCamp
June 1, 2026 - When it's imported by another script, ... calculation into their own program. ... The from..import statement allows you to import specific functions/variables from a module instead of importing everything....
Top answer
1 of 16
629

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 import statements. Don't need to add any additional imports to start using another item from the module
  • Cons:
    • Typing module.foo in your code can be tedious and redundant (tedium can be minimized by using import module as mo then typing mo.foo)

from module import foo

  • Pros:
    • Less typing to use foo
    • More control over which items of a module can be accessed
  • Cons:
    • To use a new item from the module you have to update your import statement
    • You lose context about foo. For example, it's less clear what ceil() does compared to math.ceil()

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.

2 of 16
305

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.

🌐
Python.org
discuss.python.org › python help
Import or from for modules - Python Help - Discussions on Python.org
August 24, 2022 - I came across this in my reading. This was at the top of the script. My questions are: Why would you use “from” if you are loading all if it? I understood “from” was for importing parts of a module, example: from math import sin. Not the whole module.
🌐
GeeksforGeeks
geeksforgeeks.org › python › import-module-python
Import module in Python - GeeksforGeeks
April 25, 2026 - from math import * print(pi) # Accessing the constant 'pi' print(factorial(6)) # Using the factorial function ... While convenient, this method is not recommended in larger programs as it can lead to conflicts with existing variables and functions. When importing a module that doesn’t exist or isn't installed, Python raises an ImportError.
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › programming › python
What does "from . import *" mean. - Raspberry Pi Forums
from foo import * Python will go off looking in $PYTHONPATH for foo.py, and import all of its methods when it is found. If you specific a path, such as . for the current working directory, Python will read all of the *.py files in that directory and import their methods.
🌐
Medium
medium.com › @officialyrohanrokade › mastering-python-imports-and-module-management-a-deep-dive-into-import-keywords-folder-d92aa1daaaf5
Mastering Python Imports and Module Management: A Deep Dive into Import Keywords, Folder Structures, and Module Control. | by Rohan Rokade | Medium
February 10, 2024 - Importing a module in Python is as simple as using the import keyword followed by the name of the module.This statement imports the entire module, making its contents accessible using dot notation.
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-import-modules-in-python-3
How To Import Modules in Python 3 | DigitalOcean
Learn how to import modules in Python 3 using import, from, and aliases. Discover best practices and examples for organizing reusable Python code.
Top answer
1 of 11
265
The issue comes when you have modules which contain things with the same name. Suppose you need to use the modules math, cmath, and numpy all in the same code (god help you). Each of these modules defines the trig functions, sin, cos, and tan; and each does something slightly different. So if you use a from import: from math import * from cmath import * from numpy import * what happens when I write sin(x)? What if I import like this? from cmath import * from numpy import * from math import * No, better to import the modules and reference that way. import math import cmath import numpy That way I can say which implementation I need with something like numpy.sin or cmath.sin. If there's something that you're using a lot and it's tedious to name the module each time, you could import just that thing by name. from dataclasses import dataclass from functools import wraps from math import sin, cos, tan, pi
2 of 11
22
The most important difference is that import x essentially gives you access to the x namespace where you can use its contents with syntax like x.foo(), which would call x’s function foo. from x import *, on the other hand, will import all of x’s info into your current namespace. This way, when you type foo(), you’re calling x’s function without having to use the namespace dot syntax to reach it. While this seems more convenient for some cases, it is considered bad practice. By importing everything into your current ns, it because difficult to understand where a function (or whatever) is coming from, and if you have any problems with the * imported info, it becomes significantly more problematic to debug. Additionally, as others pointed out in other comments, if you have functions or something which share the same name, then importing with * makes it far more difficult to understand where your foo() is coming from, which can lead to problems. That said, I would definitely encourage you not to forget it, because it’s a good tool to have when writing throwaway scripts for quick debugging or when you’re in an interactive shell session.
🌐
Mend
mend.io › blog › developer › python import: mastering the advanced features
Python Import: Advanced Techniques Explained
November 8, 2023 - Python offers two primary ways to import modules and packages: absolute and relative imports. Absolute imports specify the complete path to the module or package you want to use, while relative imports reference modules and packages relative ...