从模块动态导入所有内容 (*)

发布于 2024-10-01 11:45:38 字数 263 浏览 4 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

猥琐帝 2024-10-08 11:45:38

使用 update 进行字典:

globals().update(importlib.import_module('some.package').__dict__)

注意,使用 a_module.__dict__from a_module import * 不同,因为所有名称都是“导入”的,而不仅仅是来自 __all__ 的名称以 _ 开头。

Use update for dicts:

globals().update(importlib.import_module('some.package').__dict__)

Note, that using a_module.__dict__ is not the same as from a_module import *, because all names are "imported", not only those from __all__ or not starting with _.

甜嗑 2024-10-08 11:45:38

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

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

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

例如,假设您的类名为 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')

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')

以下内容是非常罪恶的,会让你陷入炼狱或更糟糕的

# module_a.py
myvar = "hello"

# module_b.py
import inspect
def dyn_import_all(modpath):
    """Incredibly hackish way to load into caller's global namespace"""
    exec('from ' + modpath + ' import *', inspect.stack()[1][0].f_globals)

# module_c.py
from module_b import dyn_import_all
def print_from(modpath):
    dyn_import_all(modpath)
    print(myvar)

演示:

>>> import module_c
>>> module_c.print_from("module_a")
hello

The following is highly sinful and will condemn you to purgatory or worse

# module_a.py
myvar = "hello"

# module_b.py
import inspect
def dyn_import_all(modpath):
    """Incredibly hackish way to load into caller's global namespace"""
    exec('from ' + modpath + ' import *', inspect.stack()[1][0].f_globals)

# module_c.py
from module_b import dyn_import_all
def print_from(modpath):
    dyn_import_all(modpath)
    print(myvar)

Demo:

>>> import module_c
>>> module_c.print_from("module_a")
hello
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文