Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list modules as strings and import them

I have a bunch of modules that I need to import. For reasons I not permitted to explain the module names must be stored as strings in a list. In other words I need to do the following:

modules_to_import = ['module1', 'module2', 'module3']
import modules_to_import

Does anybody know if I can to that in python?

like image 504
flashburn Avatar asked Jun 27 '26 05:06

flashburn


1 Answers

Use importlib.import_module:

imported_modules = {m: importlib.import_module(m) for m in modules_to_import}

If you want to access the modules as global variables, you'll have to do some hacky stuff, such as assigning to globals():

for module in modules_to_import:
    globals()[module] = importlib.import_module(module)
like image 79
Francisco Avatar answered Jun 29 '26 18:06

Francisco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!