如何使用importlib从模块导入*?

Ale*_*x I 10 python python-import

我想完成与from module import *使用 importlib相同的结果。

这个问题Importing module with a local name using importlib描述了如何做import module as mod,这是相关但不一样的。

don*_*mus 15

要模拟,from X import *您必须导入模块,然后将适当的名称合并到全局命名空间中。

# 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})
Run Code Online (Sandbox Code Playgroud)