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

Mic*_*ael 3 python

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

importlib.import_module('path.to.module', '*')
Run Code Online (Sandbox Code Playgroud)

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

Nam*_* VU 6

这是@HaiVu 答案的简短版本,它引用了@Bakuriu 的这个解决方案

import importlib

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

# make the variable global
globals().update(mod.__dict__)
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 除了用户定义的变量之外,这还将导入很多东西

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


Hai*_* Vu 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)
Run Code Online (Sandbox Code Playgroud)