YouTip LogoYouTip

Python3 Func __Import__

## Python `__import__()` Function The `__import__()` function is a built-in Python function used to import modules dynamically at runtime. It serves as the underlying implementation of the standard `import` statement. While developers typically use `import` or `from ... import ...` for static imports, `__import__()` allows you to import modules using string variables. This is highly useful for advanced use cases such as plugin architectures, lazy loading, and dynamic dependency injection. --- ## Syntax and Parameters ### Syntax ```python __import__(name, globals=None, locals=None, fromlist=(), level=0) ``` ### Parameters * **`name`** (Required): * **Type**: `str` * **Description**: The name of the module you want to import. * **`globals`** (Optional): * **Type**: `dict` * **Description**: Global context dictionary (usually `globals()`). It helps determine the context of the import, especially for relative imports. * **`locals`** (Optional): * **Type**: `dict` * **Description**: Local context dictionary (usually `locals()`). Like `globals`, it is used to interpret the package context. * **`fromlist`** (Optional): * **Type**: `tuple` or `list` of strings * **Description**: Specifies the submodules or objects to import from the module (equivalent to `from module import object1, object2`). * **`level`** (Optional): * **Type**: `int` * **Description**: Specifies whether to use absolute or relative imports. `0` (default) means perform absolute imports. Positive values indicate the number of parent directories to search relative to the current module's directory. ### Return Value * Returns the imported **module object**. --- ## Code Examples ### Example 1: Basic Usage This example demonstrates how to perform basic module imports and how to import specific attributes or submodules using the `fromlist` parameter. ```python # 1. Dynamically import a standard module os = __import__('os') print(os.getcwd()) # Output: /your/current/working/directory # 2. Import a specific class/attribute from a module using fromlist # This is equivalent to: from collections import Counter collections = __import__('collections', fromlist=['Counter']) Counter = collections.Counter print(Counter([1, 2, 2, 3])) # Output: Counter({2: 2, 1: 1, 3: 1}) ``` --- ### Example 2: Dynamic and Lazy Loading This example shows how to import modules dynamically using string variables, loop through a list of module names, and implement lazy loading (on-demand loading). ```python # 1. Import a module based on a string variable module_name = "json" mod = __import__(module_name) print(mod.dumps({"key": "value"})) # Output: {"key": "value"} # 2. Dynamically import multiple modules in a loop modules = ['math', 'random', 'datetime'] for name in modules: mod = __import__(name) print(f"{name}: {mod.__name__}") # Output: # math: math # random: random # datetime: datetime # 3. Lazy loading (load a module only when a function is called) def get_module(mod_name): return __import__(mod_name) # The 'math' module is loaded only at this point math_mod = get_module('math') print(math_mod.sqrt(16)) # Output: 4.0 ``` --- ## Important Considerations While `__import__()` is a powerful built-in function, it has some quirks and is generally considered a low-level API. Keep the following in mind: 1. **Return Value Behavior with Packages**: When importing a nested module (e.g., `__import__('pkg.subpkg')`), the function returns the **top-level** package (`pkg`), not the nested submodule (`subpkg`), unless you provide a non-empty `fromlist`. 2. **Recommended Alternative**: For most dynamic import scenarios, it is highly recommended to use **`importlib.import_module()`** instead of `__import__()`. The `importlib` module was introduced in Python 3 to provide a cleaner, more user-friendly programmatic interface for imports: ```python import importlib # Cleaner and returns the actual target submodule directly subpkg = importlib.import_module('pkg.subpkg') ```
← Python3 Func DelattrPython3 Func Compile β†’