Python importThe () function
__import__() is a built-in Python function used to import modules dynamically.
__import__() Is import It is the underlying implementation of the statement, allowing modules to be imported dynamically at runtime. It is very useful for plugin systems, lazy loading, and similar scenarios.
Word meaning: __import__ 是 Python 的内置导入函数。
Basic syntax and parameters
Syntax format
__import__(name, globals=None, locals=None, fromlist=(), level=0)
Parameter Description
- Parameter name:
- Type: string
- Description: the name of the module to import.
- Parameter fromlist(optional):
- Type: tuple
- Description: the list of submodules or attributes to import from the module.
Function description
- Return Value: returns the imported module object.
Example
Example 1: basic usage
Example
# Import a module dynamically
os = __import__('os')
print(os.getcwd()) # Output: current working directory
# Import a submodule
requests = __import__('collections', fromlist=['Counter'])
print(requests.Counter) # Output:
os = __import__('os')
print(os.getcwd()) # Output: current working directory
# Import a submodule
requests = __import__('collections', fromlist=['Counter'])
print(requests.Counter) # Output:
Result:
The way to import modules.
Example 2: dynamic import
Example
# Import a module based on a string
module_name = "json"
mod = __import__(module_name)
print(mod.dumps({"key": "value"})) # Output: {"key": "value"}
# Import multiple modules dynamically
modules = ['math', 'random', 'datetime']
for name in modules:
mod = __import__(name)
print(f"{name}: {mod.__name__}")
# Lazy import (load on demand)
def get_module(mod_name):
return __import__(mod_name)
math_mod = get_module('math')
print(math_mod.sqrt(16)) # Output: 4.0
module_name = "json"
mod = __import__(module_name)
print(mod.dumps({"key": "value"})) # Output: {"key": "value"}
# Import multiple modules dynamically
modules = ['math', 'random', 'datetime']
for name in modules:
mod = __import__(name)
print(f"{name}: {mod.__name__}")
# Lazy import (load on demand)
def get_module(mod_name):
return __import__(mod_name)
math_mod = get_module('math')
print(math_mod.sqrt(16)) # Output: 4.0
Result:
Dynamic import has many uses in real applications.
__import__() is the core of Python's dynamic import mechanism.
Python3 built-in function