I would like to import all objects from a library by variable. I know how to import all objects from a library:
from package import *
I know how to import a library by variable:
import importlib
var = 'package'
package = importlib.import_module(var)
However, I cannot figure out how to combine these two goals. It does not look like importlib.import
supports this. Can anyone help?
Note: I am aware of the dangers of skirting namespaces in this way (and anyone using potential answers to my inquiry should familiarize themselves with the dangers). I only plan to use this for rapid development and testing of some algorithms, and plan to release my code with explicit names of individual objects from my files.
Edit: I came up with a minimal example. Suppose I have three files in the same directory:
aux1.py
var = 'aux2'
aux2.py
a = 0
b = 1
main.py
import importlib
from aux1 import var
aux2 = importlib.import_module(var)
If I run main.py, I can access a
and b
as aux2.a
and aux2.b
, but I'd like them to be globals instead. What would the last line of main.py
need to be in order to do this?
You could iterate through the __dict__
attribute of the module returned from import_module
, and add that item to globals()
if it doesn't start with __
.
import importlib
var = 'package'
package = importlib.import_module(var)
for name, value in package.__dict__.items():
if not name.startswith("__"):
globals()[name] = value
If you only want to import certain members of package
, you could use getattr()
with a default of None
:
imports = ['obj1', 'obj2', 'obj3']
for name in imports:
value = getattr(package, name, None)
if value is not None:
globals()[name] = value