如何使用importlib从模块导入*?[重复]


问题内容

这个问题已经在这里有了答案

动态导入Python模块 (4个答案)

Python 3中星号导入的功能形式是什么 (1个答案)

3年前关闭。

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

这个问题,使用importlib使用本地名称导入模块,描述了import module as mod相关但不相同的方法。


问题答案:

要进行仿真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})