1

The file module_x has

module_x.py

A = 'x'

And the following script will print 'x' from module_x.py, which is what I need.

A = 'a'

from module_x import *
print(A)  # x

However, I need to dynamically import the module so I use importlib for it. However, the following code prints 'a'.

from importlib import import_module

A = 'a'

m = 'module_x'  # m will be passed as a parameter
x = import_module(m) 
print(A)  # a

The value of x.A is 'x', but I want the import_module() to assign A to 'x'.

ca9163d9
  • 27,283
  • 64
  • 210
  • 413
  • 1
    Possible dupe [Importing everything ( * ) dynamically from a module](https://stackoverflow.com/q/4116061/674039) – wim Nov 12 '21 at 23:06

1 Answers1

1

this should do it:

globals().update(import_module("module").__dict__)

In case you want to import something specific

var = import_module("module").var
  • 2
    Don't blindly update globals like that. The module namespace (i.e. the `__dict__` attribute) usually has a lot more stuff in it than a *-import will take. This may break the importing-from-module by accidentally overwriting a bunch of it's attributes such as `__name__`, `__package__`, `__loader__`, `__spec__`, `__doc__`... – wim Nov 12 '21 at 22:52
  • Will filtering out these `__x__` attributes be good enough? – ca9163d9 Nov 12 '21 at 22:56
  • @ca9163d9 No. If `module_x` namespace is within your control, define and `__all__` variable in it and access that. I don't know any other way to do this with `importlib.import_module`, it doesn't seem to expose *-imports dynamically. – wim Nov 12 '21 at 22:59