Python __import__() Function

Python3 内置函数Python3 Built-in Functions


__import__()It is a built-in function in Python used for dynamically importing modules.

__import__()YesimportIt is the underlying implementation of the import statement, allowing modules to be dynamically imported at runtime. It is very useful for scenarios such as plugin systems and lazy loading.

Word Definitions: __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: A list of submodules or attributes to import from the module.

Function Description

  • Return Value: Returns the imported module object.

Examples

Example 1: Basic Usage

Example

# Dynamically import module
os = __import__('os')
print(os.getcwd())  # Output: current working directory

# Import submodule
requests = __import__('collections', fromlist=['Counter'])
print(requests.Counter)  # Output: <class 'collections.Counter'>

Output:

Ways to import modules.

Example 2: Dynamic Import

Example

# Import module based on string
module_name = "json"
mod = __import__(module_name)
print(mod.dumps({"key": "value"}))  # Output: {"key": "value"}

# Dynamically import multiple modules
modules = ['math', 'random', 'datetime']
for name in modules:
    mod = __import__(name)
    print(f"{name}: {mod.__name__}")

# Lazy import (on-demand loading)
def get_module(mod_name):
    return __import__(mod_name)

math_mod = get_module('math')
print(math_mod.sqrt(16))  # Output: 4.0

Output:

Dynamic import has various uses in practical applications.

__import__()It is the core of Python's dynamic import mechanism.


Python3 内置函数Python3 Built-in Functions


Other Extensions