How to dynamically import modules?

Dan G picture Dan G · Feb 22, 2017 · Viewed 16.8k times · Source

I am trying to import modules dynamically in Python. Right now, I have a directory called 'modules' with two files inside; they are mod1.py and mod2.py. They are simple test functions to return time (ie. mod1.what_time('now') returns the current time).

From my main application, I can import as follows :

sys.path.append('/Users/dxg/import_test/modules')
import mod1

Then execute :

mod1.what_time('now') 

and it works.

I am not always going to know what modules are available in the dirctory. I wanted to import as follows :

tree = []
tree = os.listdir('modules')

sys.path.append('/Users/dxg/import_test/modules')

for i in tree:
  import i

However I get the error :

ImportError: No module named i

What am I missing?

Answer

Uriel picture Uriel · Feb 22, 2017

The import instruction does not work with variable contents (as strings) (see extended explanation here), but with file names. If you want to import dynamically, you can use the importlib.import_module method:

import importlib
tree = os.listdir('modules')

...

for i in tree:
    importlib.import_module(i)

Note:

  • You can not import from a directory where the modules are not included under Lib or the current directory like that (adding the directory to the path won't help, see previous link for why). The simplest solution would be to make this directory (modules) a package (just drop an empty __init__.py file there), and call importlib.import_module('..' + i, 'modules.subpkg') or use the __import__ method.

  • You might also review this question. It discusses a similar situation.