22

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.

Community
  • 1
  • 1
Alex I
  • 19,689
  • 9
  • 86
  • 158

1 Answers1

28

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})
donkopotamus
  • 22,114
  • 2
  • 48
  • 60
  • 1
    If X is a package, you also need to load any submodules listed in `__all__` but not yet imported. `__import__` will handle this for you if you specify `fromlist=['*']`; with importlib, I think you need to do it manually. – user2357112 Mar 28 '17 at 02:20
  • At least in python3 you need `globals().update(...)` – pevogam Dec 23 '19 at 22:20