🌐
Python documentation
docs.python.org › 3 › reference › import.html
5. The import system — Python 3.15.1 documentation
Python code in one module gains access to the code in another module by the process of importing it. The import statement is the most common way of invoking the import machinery, but it is not the ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-import-function
__import__() function in Python - GeeksforGeeks
July 11, 2025 - __import__() is a built-in function in Python that is used to dynamically import modules. It allows us to import a module using a string name instead of the regular "import" statement.
🌐
W3Schools
w3schools.com › python › python_modules.asp
Python Modules
There are several built-in modules in Python, which you can import whenever you like.
🌐
Real Python
realpython.com › python-import
Python import: Advanced Techniques and Tips – Real Python
July 8, 2020 - In practice, a module usually corresponds to one .py file containing Python code. The true power of modules is that they can be imported and reused in other code.
🌐
Python
docs.python.org › 3 › library › importlib.html
importlib — The implementation of import
One is to provide the implementation of the import statement (and thus, by extension, the __import__() function) in Python source code. This provides an implementation of import which is portable to any Python interpreter.
🌐
GeeksforGeeks
geeksforgeeks.org › python › import-module-python
Import module in Python - GeeksforGeeks
April 25, 2026 - The import statement is the most common way to bring external functionality into your Python program.
🌐
OpenClassrooms
openclassrooms.com › us › courses › 6900846-set-up-a-python-environment › 6989471-import-python-packages-and-modules
Import Python Packages and Modules - OpenClassrooms
We import third-party Python packages into Python files in the same way as we import modules from the Python Standard Library into Python files.
🌐
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 - Python 3 ... sys.path always includes the path of the script invoked on the command line and is agnostic to the working directory on the command line. importing a package is conceptually the same as importing that package’s __init__.py file
Top answer
1 of 1
116

How to use python's __import__() function properly?

There are two kinds of uses:

  • direct importing
  • a hook to alter import behavior

For the most part, you don't really need to do either.

For user-space importing

Best practice is to use importlib instead. But if you insist:

Trivial usage:

>>> sys = __import__('sys')
>>> sys
<module 'sys' (built-in)>

Complicated:

>>> os = __import__('os.path')
>>> os
<module 'os' from '/home/myuser/anaconda3/lib/python3.6/os.py'>
>>> os.path
<module 'posixpath' from '/home/myuser/anaconda3/lib/python3.6/posixpath.py'>

If you want the rightmost child module in the name, pass a nonempty list, e.g. [None], to fromlist:

>>> path = __import__('os.path', fromlist=[None])
>>> path
<module 'posixpath' from '/home/myuser/anaconda3/lib/python3.6/posixpath.py'>

Or, as the documentation declares, use importlib.import_module:

>>> importlib = __import__('importlib')
>>> futures = importlib.import_module('concurrent.futures')
>>> futures
<module 'concurrent.futures' from '/home/myuser/anaconda3/lib/python3.6/concurrent/futures/__init__.py'>

Documentation

The docs for __import__ are the most confusing of the builtin functions.

__import__(...)
    __import__(name, globals=None, locals=None, fromlist=(), level=0) -> module

    Import a module. Because this function is meant for use by the Python
    interpreter and not for general use it is better to use
    importlib.import_module() to programmatically import a module.

    The globals argument is only used to determine the context;
    they are not modified.  The locals argument is unused.  The fromlist
    should be a list of names to emulate ``from name import ...'', or an
    empty list to emulate ``import name''.
    When importing a module from a package, note that __import__('A.B', ...)
    returns package A when fromlist is empty, but its submodule B when
    fromlist is not empty.  Level is used to determine whether to perform 
    absolute or relative imports. 0 is absolute while a positive number
    is the number of parent directories to search relative to the current module.

If you read it carefully, you get the sense that the API was originally intended to allow for lazy-loading of functions from modules. However, this is not how CPython works, and I am unaware if any other implementations of Python have managed to do this.

Instead, CPython executes all of the code in the module's namespace on its first import, after which the module is cached in sys.modules.

__import__ can still be useful. But understanding what it does based on the documentation is rather hard.

Full Usage of __import__

To adapt the full functionality to demonstrate the current __import__ API, here is a wrapper function with a cleaner, better documented, API.

def importer(name, root_package=False, relative_globals=None, level=0):
    """ We only import modules, functions can be looked up on the module.
    Usage: 

    from foo.bar import baz
    >>> baz = importer('foo.bar.baz')

    import foo.bar.baz
    >>> foo = importer('foo.bar.baz', root_package=True)
    >>> foo.bar.baz

    from .. import baz (level = number of dots)
    >>> baz = importer('baz', relative_globals=globals(), level=2)
    """
    return __import__(name, locals=None, # locals has no use
                      globals=relative_globals, 
                      fromlist=[] if root_package else [None],
                      level=level)

To demonstrate, e.g. from a sister package to baz:

baz = importer('foo.bar.baz')    
foo = importer('foo.bar.baz', root_package=True)
baz2 = importer('bar.baz', relative_globals=globals(), level=2)

assert foo.bar.baz is baz is baz2

Dynamic access of names in the module

To dynamically access globals by name from the baz module, use getattr. For example:

for name in dir(baz):
    print(getattr(baz, name))

Hook to alter import behavior

You can use __import__ to alter or intercept importing behavior. In this case, let's just print the arguments it gets to demonstrate we're intercepting it:

old_import = __import__

def noisy_importer(name, locals, globals, fromlist, level):
    print(f'name: {name!r}')
    print(f'fromlist: {fromlist}')
    print(f'level: {level}')
    return old_import(name, locals, globals, fromlist, level)

import builtins
builtins.__import__ = noisy_importer

And now when you import you can see these important arguments.

>>> from os.path import join as opj
name: 'os.path'
fromlist: ('join',)
level: 0
>>> opj
<function join at 0x7fd08d882618>

Perhaps in this context getting the globals or locals could be useful, but no specific uses for this immediately come to mind.

Find elsewhere
🌐
YouTube
youtube.com › watch
Importing Your Own Python Modules Properly - YouTube
Today we learn how to properly import your own Python modules and also what the __init__.py file is about.◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾📚 Programming Books & Merch 📚🐍 ...
Published: July 6, 2022
🌐
OpenClassrooms
openclassrooms.com › us › courses › 6902811-learn-python-basics › 7091081-import-python-libraries
Import Python Libraries - OpenClassrooms
Pip is a Python package manager that lets you install and manage your external libraries. The import keyword lets you import entire libraries or specific library functions into your code.
🌐
The Python Coding Stack
thepythoncodingstack.com › the python coding stack › the shortest python `import` tutorial • a picture story
The Shortest Python `import` Tutorial • A Picture Story
January 22, 2025 - The difference between the three is best understood through Python's namespaces. When you import the whole module, such as import some_module, the name some_module is part of the program's main namespace. However, the module's contents aren't. They're in the module's namespace.
🌐
Medium
medium.com › data-science › understanding-python-imports-init-py-and-pythonpath-once-and-for-all-4c5249ab6355
Understanding Python imports, __init__.py and pythonpath — once and for all | by Dr. Varshita Sher | TDS Archive | Medium
January 25, 2025 - It is a list of directories that Python will search once it is done looking at the cached modules and Python standard library modules. Let’s see what our system path contains at this very moment (by commenting out previous lines of code in example2.py). #example2.py# import example1 # print("The imported string is: ", example1.MY_EX1_STRING) # example1.yolo(10)import sys print(sys.path)
🌐
Career Karma
careerkarma.com › blog › python › python import statements: a guide
Python Import Statements: A Guide | Career Karma
December 1, 2023 - The import statement syntax is: import modulename. Python is accompanied by a number of built-in modules that allow you to perform common operations in your code. int(), for example, converts a value to an integer.
🌐
DataCamp
datacamp.com › tutorial › modules-in-python
Python Modules Tutorial: Importing, Writing, and Using Them | DataCamp
June 1, 2026 - Master Python for data science and gain in-demand skills. ... To use the functionality present in any module, you have to import it into your current program. You need to use the import keyword along with the desired module name.
🌐
YouTube
youtube.com › watch
Python Tutorial for Beginners 9: Import Modules and Exploring The Standard Library - YouTube
In this Python Beginner Tutorial, we will begin learning how to import modules in Python. We will learn how to import modules we have written, as well as mod...
Published: May 17, 2017
🌐
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.
🌐
Mend
mend.io › blog › developer › python import: mastering the advanced features
Python Import: Mastering the Advanced Features
November 8, 2023 - Go beyond basic Python import statements with importlib, dynamic imports, and importlib.resources for cleaner, faster-loading packages overall.
🌐
W3Schools
w3schools.com › python › gloss_python_module_import_from.asp
Python Import From Module
Python Examples Python Compiler ... Q&A Python Training ... You can choose to import only parts from a module, by using the from keyword....