1

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))
2
  • 1
    It's one thing to use from foo import * when you know what foo is. How will you even know what was imported if you don't know the value of active_data_module? Commented Jan 23, 2021 at 22:08
  • @chepner the active data module is generated at runtime from configurations that are user defined. Commented Jan 23, 2021 at 22:43

2 Answers 2

1

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))
Sign up to request clarification or add additional context in comments.

Comments

0

Using Peter Wood's answer, I created a small utility function:

import importlib

def import_everything_from_module_by_name(module_name):
    globals().update(vars(importlib.import_module(module_name)))

modules_for_import = [
    module_a,
    module_b,
    module_c
    ]

for module_name in modules_for_import:
    import_everything_from_module_by_name(module_name)

1 Comment

Just to note, this will only update globals for that particular module. It might not behave the way you think if you call the function from a different module.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.