i need monkey-patch library replace instance of symbol, , it's getting referenced function closures. need copy functions (since need access original unpatched version of function well), __closure__
immutable, , can't copy.copy
it, how can create new closure cells objects in python 2.7?
i example given function
def f(): def incorrectfunction(): return 0 def g(): return incorrectfunction() return g def correctfunction(): return 42 func = f() patched_func = patchit(f) # replace "incorrectfunction" print func(), patched_func()
and want see
0, 42
the simple way make closure cell make closure:
def make_cell(val=none): x = val def closure(): return x return closure.__closure__[0]
if want reassign cell's contents, you'll need make c api call:
import ctypes pycell_set = ctypes.pythonapi.pycell_set # ctypes.pythonapi functions need have argtypes , restype set manually pycell_set.argtypes = (ctypes.py_object, ctypes.py_object) # restype defaults c_int here, might explicit pycell_set.restype = ctypes.c_int pycell_set(cell, new_value)
cpython only, of course.