我们如何在被叫方中修改呼叫者中的值?

时间:2019-10-23 11:37:33

标签: python python-3.x cpython

我们如何在被叫方中修改呼叫者中的值?

在下面的代码中,为什么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()

1 个答案:

答案 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