Importing Modules from String Variables with "__import__"
When attempting to document specific submodules within the matplotlib (MPL) library, it may be necessary to import these submodules from strings. However, using the "__import__" function can produce unexpected results compared to standard import statements.
Problem:
Importing a submodule using "__import__" (e.g., __import__('matplotlib.text')) does not fully load the submodule's contents as expected. Upon comparing the list of attributes obtained from both "__import__" and a regular import, it is evident that "__import__" includes base definitions from matplotlib along with extraneous elements but lacks crucial classes from the target submodule.
Solution:
To load a submodule from a string using "__import__", specify an empty list as the second argument (fromlist):
import matplotlib.text as text x = dir(text) i = __import__('matplotlib.text', fromlist='') y = dir(i)
This revised code effectively loads the desired submodule, yielding the expected list of attributes.
Alternatively, in Python versions 3.1 or later, one can utilize the importlib module:
import importlib i = importlib.import_module("matplotlib.text") y = dir(i)
Notes:
The above is the detailed content of Why Does `__import__` Fail to Fully Import Matplotlib Submodules, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!