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

Python 如何使用importlib从模块导入*?,python,python-import,Python,Python Import,我想使用importlib实现与模块导入*中的相同的结果 此问题描述了如何将模块作为mod导入,这是相关的,但不是相同的。要从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 = m

我想使用importlib实现与模块导入*中的
相同的结果


此问题描述了如何将模块作为mod导入,这是相关的,但不是相同的。

要从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})

如果X是一个包,您还需要加载
\uuuuu all\uuuuuuu>中列出但尚未导入的任何子模块<如果您指定
fromlist=['*']
,code>\uuuuuuuuuu导入\uuuuuuu
将为您处理此问题;对于importlib,我认为您需要手动执行。至少在python3中,您需要
globals().update(…)