Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically import modules?

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?

like image 633
Dan G Avatar asked Feb 22 '17 20:02

Dan G


People also ask

What is dynamic module in Python?

This module defines utility functions to assist in dynamic creation of new types. It also defines names for some object types that are used by the standard Python interpreter, but not exposed as builtins like int or str are.

What is dynamic import in angular?

TypeScript 2.4 added support for dynamic import() expressions, which allow us to asynchronously load and execute ECMAScript modules on demand. This means that we can conditionally and lazily import other modules and libraries.

Why do we need to use dynamic imports?

Dynamic module imports play a very important role if you want your code to be fast and more performant. Most of the time, you don't have to load all those heavy and bulky files in one go. It will be super helpful if we can somehow import those files whenever they are required.


1 Answers

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.

like image 189
Uriel Avatar answered Oct 01 '22 19:10

Uriel