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

时间:2015-07-09 01:07:48

标签: python

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

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

我没有对导入的属性进行名称间隔的原因是故意的。

2 个答案:

答案 0 :(得分:5)

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

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)

答案 1 :(得分:2)

以下是@HaiVu answer的简短版本,引用this solution from @Bakuriu

import importlib
#import the module
mod = importlib.import_module('collections')
#make the variable global
globals().update(mod.__dict__)

注意:

  • 这会在用户定义的变量旁边导入很多东西

  • @HaiVu解决方案做得最好,即。仅导入用户定义的变量

相关问题