When working with nested libraries, a common task is to dynamically import submodules using a string variable as the import path. However, the "__import__" function can yield different results compared to a typical import statement.
In your example, when using "__import__" without specifying the "fromlist" argument:
i = __import__('matplotlib.text')
the imported module i includes both the base matplotlib module and something additional. To specifically import the matplotlib.text submodule, you can modify the code to:
i = __import__('matplotlib.text', fromlist=[''])
In Python 3.1 or later, you can also use the importlib module:
import importlib i = importlib.import_module("matplotlib.text")
Here are a few additional notes to consider:
importlib.import_module("feature.email")
The above is the detailed content of How Do `__import__` and `importlib.import_module` Differ When Importing Modules from Strings in Python?. For more information, please follow other related articles on the PHP Chinese website!