python - 如何在命名空间字典中执行函数?

标签 python python-3.x

假设我有以下命令:

In [6]: scope
Out[6]: {'bar': <function bar>, 'foo': <function foo>}

foobar是:

def foo():
    return 5

def bar(x):
    return foo() + x

我要运行 bar(1) , 但它需要找到 foo() .有没有办法运行bar()scope命名空间,以便它找到 foo()

我不太清楚 scope 中的哪个函数bar会需要,所以我需要一个通用的运行方法barscope命名空间。我没有源代码,也无法修改任何一个函数来接受字典。

函数似乎有一个 __closure__属性,但它是不可变的。还有一个__globals__属性,但这只是指向 globals() .我在更新 locals() 的 SO 上看到了一些答案但我想离开locals()未受影响。

我尝试了 evalscope , 但得到 NameError对于 foo :

In [12]: eval(scope['bar'](1), scope)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-12-f6305634f1da> in <module>()
----> 1 eval(scope['bar'](1), scope)

<string> in bar(x)

NameError: global name 'foo' is not defined

我缺少一些简单的方法吗?

最佳答案

一种方法是使用共享的全局字典创建新函数:

from types import FunctionType

def scopify(**kwargs):
    scoped = dict()
    for name, value in kwargs.items():
        if isinstance(value, FunctionType):
            scoped[name] = FunctionType(value.__code__, scoped, name)
        else:
            scoped[name] = value
    return scoped

scope = scopify(
    foo = lambda: baz,
    bar = lambda x: foo() + x,
    baz = 5,
)

>>> scope['foo']
5
>>> scope['bar'](10)
15
>>> scope['baz'] = 100
>>> scope['bar'](10)
110

关于python - 如何在命名空间字典中执行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21716362/

相关文章:

python - 在python中找到两个列表之间匹配索引的最快方法?

python - Django 模板和 HTML 框架集

windows - 在 Windows 上崩溃后如何保持 subprocess.Popen 控制台打开?

python - 如何在 Python 中停止 os.system()?

python - 如何获取数据帧的子组开始完成索引

python - 如何在 Python 中显示列表元素的索引?

python - 在Python中使用PhantomJS设置代理

python - redis python scan_iter 给出不同的键

python - 使用 Python 正则表达式,如何在结果中不出现空字符串的情况下将该字符串拆分为多个分隔符?

python - 通过实体 ID 检索实体