How to dynamically import modules?

19,472

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.

Share:
19,472

Related videos on Youtube

Dan G
Author by

Dan G

Updated on June 04, 2022

Comments

  • Dan G
    Dan G about 2 years

    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?