Importing module from string variable using “__import__” gives different results than a normal import statement

The __import__ function can be a bit hard to understand.

If you change

i = __import__('matplotlib.text')


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/, the code will look like importlib.import_module("")

  • Before Python 3.3 you could not import anything if there was no 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. with pytest).

Leave a Comment