Python 3 reference · Built-in Functions
Python __import__() Function
The low-level function the import statement calls. Use importlib.import_module() instead to import a module by name.
Python 3 Since 3.0
Syntax
__import__(name, globals=None, locals=None, fromlist=(), level=0)
Parameters
| Parameter | Description |
|---|---|
name |
The module name. |
globals, locals, fromlist, level optional |
Used by the import machinery. |
Return value
The imported module (for dotted names, the top-level package unless fromlist is given).
Examples
import importlib
math = importlib.import_module("math") # the recommended way
print(math.sqrt(16))
Output
4.0
json = __import__("json")
print(json.dumps({"ok": True}))
pkg = __import__("os.path")
print(pkg.__name__) # returns the top-level package, os
Output
{"ok": true}
osGood to know
__import__("a.b") returns package a, not module a.b, which surprises most people.
importlib.import_module("a.b") returns the module you asked for.
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
dir()· List the names an object has, such as attributes and methods. With no argument, list the names in the current scope.globals()· Return the dictionary of the current module's global names: variables, functions, classes and imports.- Python Modules and Imports · tutorial