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

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

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)
点赞