从模块动态导入所有内容(*) [英] Importing everything ( * ) dynamically from a module

查看:132
本文介绍了从模块动态导入所有内容(*)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python模块,我想动态导入只给出一个模块名称的字符串。通常我使用 importlib __ import __ ,这非常有效,因为我知道要从模块导入哪些对象,但有没有办法动态地相当于 import * 。还是有更好的方法?



我一般都知道使用 import * 的不良做法,但我试图导入的模块是自动的在运行中生成,我无法知道包含我正在寻址的类的确切模块。



谢谢。

解决方案

我想出了一些丑陋的hacky代码,它在python 2.6中运行。我不确定这是否是最聪明的事情,也许其他人在这里有一些见解:

  test = __import __( 'OS​​',全局(),当地人())
。在DIR K(试验):)
全局([K] =测试.__字典__ [k]的

您可能希望在此处检查以确保不覆盖全局命名空间中的任何内容。您可以避免全局部分,只需查看每个动态导入的模块,以获得您感兴趣的类。这可能比使用您导入的所有内容污染全局命名空间要好得多。



例如,假设您的类名为来自urllib2的请求



'pre> 测试= __import __( '的urllib2',全局(),当地人())
CLS =无
如果在目录 '请求' (测试):
cls = test .__ dict __ ['Request']
#你现在找到了这个课你可以使用它!
cls('http://test.com')


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.

解决方案

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:

test = __import__('os',globals(),locals())
for k in dir(test):
    globals()[k] = test.__dict__[k]

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

test = __import__('urllib2',globals(),locals())
cls = None
if 'Request' in dir(test):
    cls = test.__dict__['Request']
    # you found the class now you can use it!
    cls('http://test.com')

这篇关于从模块动态导入所有内容(*)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆