The __import__
function can be a bit hard to understand.
If you change
i = __import__('matplotlib.text')
to
i = __import__('matplotlib.text', fromlist=[''])
then i
will refer to matplotlib.text
.
In Python 3.1 or later, you can use importlib
:
import importlib
i = importlib.import_module("matplotlib.text")
Some notes
-
If you’re trying to import something from a sub-folder e.g.
./feature/email.py
, the code will look likeimportlib.import_module("feature.email")
-
Before Python 3.3 you could not import anything if there was no
__init__.py
in the folder with file you were trying to import (see caveats before deciding if you want to keep the file for backward compatibility e.g. withpytest
).