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

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

问题描述

我有一个 Python 模块,我想在仅给定模块名称字符串的情况下动态导入它.通常我使用 importlib__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?

我通常知道使用 import * 的不好做法,但是我尝试导入的模块是动态自动生成的,我无法知道包含该类的确切模块我在致辞.

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.

谢谢.

推荐答案

我想出了一些丑陋的 hacky 代码,它适用于 python 2.6.我不确定这是否是最明智的做法,也许这里的其他一些人有一些见解:

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.

例如,假设您的类名为 Request from urllib2

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天全站免登陆