Python __import__() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
Built-in

Definition

In Python, __import__(name) is the function that the import statement calls behind the scenes. math = __import__("math") does the same as import math, but the module name is a string, so it can be chosen at runtime.

Its main surprise: for a dotted name like "os.path", it returns the top-level package os, not os.path, unless you pass a non-empty fromlist. For dynamic imports in your own code, use importlib.import_module(), which simply returns the module you asked for.

__import__() is a built-in function, available without an import. Its double-underscore name signals that it is mainly for Python's own import machinery.

Syntax

Pass the module name as a string.

python
math = __import__("math")
os_path = __import__("os.path", fromlist=["join"])
CallWhat it does
__import__("math")Same module as import math.
__import__("os.path")Returns the top-level os package.
__import__("os.path", fromlist=["join"])Returns os.path itself.
importlib.import_module("os.path")The recommended way.

Modules are cached in sys.modules, so importing the same name again returns the same module object without re-running it.

Library declarations
python
__import__(name, globals=None, locals=None, fromlist=(), level=0)

Parameters

ParameterDescription
nameRequired. The module name, possibly dotted.
globals, localsOptional. Used only to resolve relative imports; locals is ignored.
fromlistOptional. Names to import β€œfrom” the module; non-empty means return the submodule itself.
levelOptional. 0 for absolute imports; positive for relative imports.

Return Value

Return ValueDescription
moduleThe top-level package, or the named module when fromlist is non-empty.

Python Examples

Example 1 — Import Modules from Strings

Load two modules with __import__() and check the module cache.

python
math = __import__("math")
print(math.sqrt(81))

json_module = __import__("json")
print(json_module.dumps({"ok": True}))
print(math is __import__("math"))

How It Works

  1. Same as import. __import__("math") returns the module that import math would bind.
  2. Any name you like. The result can be stored under a different variable, such as json_module.
  3. Cached. A second import of "math" returns the very same module object.
  4. Real module. JSON output uses lowercase true, proving the json module ran.

Example 2 — Why "os.path" Returns os

Compare the result with and without fromlist, keeping the output the same on every operating system.

python
top = __import__("os.path")
print(top.__name__)

os_path = __import__("os.path", fromlist=["join"])
print(os_path.__name__ in ("posixpath", "ntpath"))
print(os_path.join("docs", "intro.txt") in ("docs/intro.txt", "docs\\intro.txt"))

How It Works

  1. Top-level package. Without fromlist, the result is os, which mirrors how import os.path binds the name os.
  2. fromlist changes it. A non-empty list returns the submodule, like from os.path import join needs.
  3. Platform module. os.path is really posixpath or ntpath, so the check accepts either.
  4. Portable output. The joined path uses / or \ depending on the system; testing both keeps the output identical.

Example 3 — Use importlib.import_module() Instead

Import modules by name with the recommended API and handle a module that is not installed.

python
import importlib

for name in ["json", "collections.abc", "no_such_module_xyz"]:
    try:
        module = importlib.import_module(name)
        print(name, "->", module.__name__)
    except ModuleNotFoundError:
        print(name, "-> not installed")

abc_mod = importlib.import_module("collections.abc")
print(abc_mod is __import__("collections.abc", fromlist=["Mapping"]))

How It Works

  1. Returns what you ask for. import_module("collections.abc") gives the submodule directly, with no fromlist trick.
  2. Missing modules. An unknown name raises ModuleNotFoundError, which the loop catches.
  3. Same object. Both functions use the same cache, so the results are identical.
  4. Plugin loading. This pattern loads modules named in trusted configuration, such as plugin lists.

Frequently Asked Questions

The built-in function the import statement uses internally. It imports a module given its name as a string.
It returns the top-level package, matching how import a.b binds the name a. Pass a non-empty fromlist to get a.b.
importlib.import_module(). It returns the requested module directly and is the documented API for dynamic imports.
module = importlib.import_module(name).
No. Modules are cached in sys.modules; later imports return the cached module.

Back to the function index

See all 73 built-in function guides grouped by what they do.

Function Index →

About the author

Mari Selvan M P
Mari Selvan M P πŸ”—

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

7 people found this page helpful