通过字符串导入从模块导入*


问题内容

我知道我可以使用importlib通过字符串导入模块。如何import *使用此库重新创建功能?基本上,我想要这样的东西:

importlib.import_module('path.to.module', '*')

我不对输入的属性进行命名间隔的原因是故意的。


问题答案:

这是一个解决方案:导入模块,然后在当前名称空间中一个接一个地创建别名:

import importlib

# Import the module
mod = importlib.import_module('collections')

# Determine a list of names to copy to the current name space
names = getattr(mod, '__all__', [n for n in dir(mod) if not n.startswith('_')])

# Copy those names into the current name space
g = globals()
for name in names:
    g[name] = getattr(mod, name)