假设我有以下命令:
In [6]: scope
Out[6]: {'bar': <function bar>, 'foo': <function foo>}
和foo
和 bar
是:
def foo():
return 5
def bar(x):
return foo() + x
我要运行 bar(1)
, 但它需要找到 foo()
.有没有办法运行bar()
在scope
命名空间,以便它找到 foo()
?
我不太清楚 scope
中的哪个函数bar
会需要,所以我需要一个通用的运行方法bar
在scope
命名空间。我没有源代码,也无法修改任何一个函数来接受字典。
函数似乎有一个 __closure__
属性,但它是不可变的。还有一个__globals__
属性,但这只是指向 globals()
.我在更新 locals()
的 SO 上看到了一些答案但我想离开locals()
未受影响。
我尝试了 eval
在scope
, 但得到 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/