Eugene K
Eugene K

Reputation: 3457

Import Numerous Modules

I'm working on my making a simple tester for my project, my project is a group of many self contained python files (e.g. solution1.py, solution2.py, etc.). My tester works, but it requires me to do import solution1, solution2, ..., how can I just import everything that matches a pattern?

I have tried creating a list of the files using glob and importing the list, but that gave:

ImportError: No module named solutions

I tried to eval() it, but that was 'invalid syntax'.

Perhaps the question is, how can I interpolate a list of strings into a list of modules?

Thanks!

Upvotes: 2

Views: 67

Answers (2)

Sneftel
Sneftel

Reputation: 41522

You can use importlib.import_module() to import a module named by a string.

If you wanted to construct an import statement instead, you'd need to use exec() instead of eval(). The latter can only evaluate expressions; the former executes statements.

Upvotes: 2

jwodder
jwodder

Reputation: 57610

You can import a module identified by a string with the importlib module:

import importlib

list_of_module_names = ...
for s in list_of_module_names:
    importlib.import_module(s)

Upvotes: 3

Related Questions