__import__()
The built-in __import__()
function allows you to dynamically import a module by its name, which should be provided as a string:
>>> sys = __import__("sys")
>>> sys
<module 'sys' (built-in)>
Note: The direct use of __import__()
is discouraged in favor of importlib.import_module()
.
__import__()
Signature
__import__(name, globals=None, locals=None, fromlist=(), level=0)
Arguments
Argument | Description | Default Value |
---|---|---|
name |
A module’s name as a string | Required argument |
globals |
A dictionary representing the global namespace | None |
locals |
A dictionary representing the local namespace | None |
fromlist |
A list of objects or submodules to import from the module | () |
level |
Number of parent directories to search for relative imports | 0 |
Return Value
- Returns the top-level package or module specified by
name
when thefromlist
argument is empty. - Returns the module specified by
name
whenfromlist
is not empty.
__import__()
Examples
With a simple module name as an argument:
>>> math = __import__("math")
>>> math.sqrt(16)
4.0
With a module and submodule specified in name
and using fromlist
:
>>> os_path = __import__("os.path", fromlist=[""])
>>> os_path
<module 'posixpath' (frozen)>
__import__()
Common Use Cases
The most common use cases for the __import__()
function include:
- Implementing custom import logic in advanced applications.
- Dynamically importing modules based on string input.
- Overriding the import system for specialized needs.
__import__()
Real-World Example
Suppose you want to dynamically import a module based on user input, allowing for flexible program behavior:
>>> module_name = input("Enter module name to import: ")
>>> module = __import__(module_name)
>>> print(f"{module_name} module has been imported.")
This example demonstrates how __import__()
can be used to dynamically import a module, enhancing flexibility in applications where the module to be imported is determined at runtime.
Related Resources
Tutorial
Python import: Advanced Techniques and Tips
The Python import system is as powerful as it is useful. In this in-depth tutorial, you'll learn how to harness this power to improve the structure and maintainability of your code.
For additional information on related topics, take a look at the following resources:
- Advanced Python import Techniques (Course)
- Absolute vs Relative Imports in Python (Tutorial)
- Python import: Advanced Techniques and Tips (Quiz)
- Absolute vs Relative Imports in Python (Course)