I would like to accomplish the same result as from module import *
using importlib.
This question Importing module with a local name using importlib describes how to do import module as mod
, which is related but not the same.
To emulate from X import *
you must import the module and then merge the appropriate names into the global namespace.
# get a handle on the module
mdl = importlib.import_module('X')
# is there an __all__? if so respect it
if "__all__" in mdl.__dict__:
names = mdl.__dict__["__all__"]
else:
# otherwise we import all names that don't begin with _
names = [x for x in mdl.__dict__ if not x.startswith("_")]
# now drag them in
globals().update({k: getattr(mdl, k) for k in names})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With