Home Python Built-in Functions __import__() Python __import__() Function 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.
math = __import__("math")
os_path = __import__("os.path", fromlist=["join"]) Call What 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 __import__(name, globals=None, locals=None, fromlist=(), level=0) Parameters Parameter Description name Required. The module name, possibly dotted. globals, locals Optional. Used only to resolve relative imports; locals is ignored. fromlist Optional. Names to import βfromβ the module; non-empty means return the submodule itself. level Optional. 0 for absolute imports; positive for relative imports.
Return Value Return Value Description module The top-level package, or the named module when fromlist is non-empty.
Python Examples 1. Import by name 2. Top-level vs fromlist 3. Preferred way Example 1 — Import Modules from Strings Load two modules with __import__() and check the module cache.
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 Same as import. __import__("math") returns the module that import math would bind.Any name you like. The result can be stored under a different variable, such as json_module.Cached. A second import of "math" returns the very same module object.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.
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 Top-level package. Without fromlist, the result is os, which mirrors how import os.path binds the name os.fromlist changes it. A non-empty list returns the submodule, like from os.path import join needs.Platform module. os.path is really posixpath or ntpath, so the check accepts either.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.
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"])) json -> json
collections.abc -> collections.abc
no_such_module_xyz -> not installed
True How It Works Returns what you ask for. import_module("collections.abc") gives the submodule directly, with no fromlist trick.Missing modules. An unknown name raises ModuleNotFoundError, which the loop catches.Same object. Both functions use the same cache, so the results are identical.Plugin loading. This pattern loads modules named in trusted configuration, such as plugin lists.Frequently Asked Questions What is __import__() in Python? The built-in function the import statement uses internally. It imports a module given its name as a string.
Why does __import__("a.b") return a? It returns the top-level package, matching how import a.b binds the name a. Pass a non-empty fromlist to get a.b.
Should I use __import__() or importlib.import_module()? importlib.import_module(). It returns the requested module directly and is the documented API for dynamic imports.
How do I import a module whose name is in a variable? module = importlib.import_module(name).
Does importing twice run the module twice? 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 Developer, cloud engineer, and technical writer
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
Helpful Share Copy link Suggestion