Skip to content Skip to sidebar Skip to footer

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 follow

Solution 1:

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():

formodule in modules_to_import:
    globals()[module] = importlib.import_module(module)

Post a Comment for "List Modules As Strings And Import Them"