我们如何在被叫方中修改呼叫者中的值?
在下面的代码中,为什么exec
不修改函数xxxx
中变量bar
的值?
def foo(xcode):
print("CODE: ", xcode)
of = inspect.currentframe().f_back
of_locals = of.f_locals
of_globals = inspect.stack()[1][0].f_globals
exec(xcode, of_globals, of_locals)
del of
def bar():
x = 1
y = 2
z = 3
foo("x = y + z")
print("x == ", x)
print("x == 6? ", x == 6)
bar()
答案 0 :(得分:2)
在exec
语句后添加以下行似乎可行:
ctypes.pythonapi.PyFrame_LocalsToFast(ctypes.py_object(of), ctypes.c_int(0))
所以,我们有:
import ctypes
def foo(xcode):
print("CODE: ", xcode)
of = inspect.currentframe().f_back
of_locals = of.f_locals
of_globals = inspect.stack()[1][0].f_globals
exec(xcode, of_globals, of_locals)
ctypes.pythonapi.PyFrame_LocalsToFast(ctypes.py_object(of), ctypes.c_int(0))
del of