Search code examples
pythonpython-importlib

Python import all * from dynamically created module


I have found many variations for importing dynamically created/named modules by reference to their names as text, but all import the module as a whole and do not seem to facilitate importing all * ....

In my case, the objects within the file are dynamically created and named, so their identities cannot be discovered beforehand.

This works, but is there a better way perhaps using importlib ?

PREFIX = "my_super_new"

active_data_module = "{0}_data_module".format(PREFIX)

exec("from {0} import *".format(active_data_module))

Solution

  • You could use vars with the module. This would return a dictionary of all attributes on the module (I think). Then you can assign the dictionary to the globals dictionary to make it accessible in the current module:

    import importlib
    
    PREFIX = "my_super_new"
    active_data_module = "{0}_data_module".format(PREFIX)
    
    module = importlib.import_module(active_data_module)
    
    globals().update(vars(module))