Python `__import__` built-in function
From the Python 3 documentation
This function is invoked by the import statement. It can be replaced [...] in order to change semantics of the import statement, but doing so is strongly discouraged as it is usually simpler to use import hooks [...]. Direct use of __import__() is also discouraged in favor of importlib.import_module().
Introduction
The __import__()
function is the underlying function that is called by the import
statement. While it’s possible to use it directly, it’s generally discouraged. For dynamically importing modules, the importlib.import_module()
function is the recommended approach.
Example
Here’s how you could use __import__()
to dynamically import the math
module:
# Dynamically import the 'math' module
math_module = __import__('math')
# Now you can use it like a regular import
print(math_module.sqrt(4)) # Output: 2.0
However, the recommended way using importlib
is:
import importlib
math_module = importlib.import_module('math')
print(math_module.sqrt(4)) # Output: 2.0