Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do from module import * using importlib? [duplicate]

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.

like image 787
Alex I Avatar asked Mar 28 '17 01:03

Alex I


Video Answer


1 Answers

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})
like image 107
donkopotamus Avatar answered Nov 04 '22 00:11

donkopotamus