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

How to do from module import * using importlib?

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

这个问题描述的是怎么做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})