从模块动态导入所有内容 (*)
我有一个 Python 模块,我想在仅给出模块名称字符串的情况下动态导入该模块。通常我使用 importlib
或 __import__
,鉴于我知道我想从模块导入哪些对象,这工作得很好,但是有没有办法做相当于 <代码>动态导入*。或者有更好的方法吗?
我知道一般来说使用 import *
是不好的做法,但是我尝试导入的模块是动态自动生成的,我无法知道包含我所在类的确切模块寻址。
谢谢。
I have a Python module that I want to dynamically import given only a string of the module name. Normally I use importlib
or __import__
and this works quite well given that I know which objects I want to import from the module, but is there a way to do the equivalent of import *
dynamically. Or is there a better approach?
I know in general its bad practice to use import *
but the modules I'm trying to import are automatically generated on the fly and I have no way of knowing the exact module which contains the class I'm addressing.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
update
进行字典:注意,使用
a_module.__dict__
与from a_module import *
不同,因为所有名称都是“导入”的,而不仅仅是来自__all__
的名称以_
开头。Use
update
for dicts:Note, that using
a_module.__dict__
is not the same asfrom a_module import *
, because all names are "imported", not only those from__all__
or not starting with_
.我想出了一些丑陋的 hacky 代码,它可以在 python 2.6 中运行。我不确定这是否是最明智的做法,也许这里的其他一些人有一些见解:
您可能想在此处进行检查以确保您没有覆盖全局名称空间中的任何内容。您可能可以避免全局部分,只需查看每个动态导入的模块以查找您感兴趣的类。这可能比用导入的所有内容污染全局命名空间要好得多。
例如,假设您的类名为 Request from urllib2
I came up with some ugly hacky code, it works in python 2.6. I'm not sure if this is the smartest thing to do though, perhaps some other people here have some insight:
You probably want to put a check here to make sure you aren't overwriting anything in the global namespace. You could probably avoid the globals part and just look through each dynamically imported module for your class of interest. This would probably be much better than polluting the global namespace with everything you are importing.
For example, say your class is named Request from urllib2
以下内容是非常罪恶的,会让你陷入炼狱或更糟糕的
演示:
The following is highly sinful and will condemn you to purgatory or worse
Demo: