How to create new closure cell objects?

前端 未结 3 1080
迷失自我
迷失自我 2021-01-15 01:41

I need to monkey-patch my library to replace an instance of a symbol, and it\'s getting referenced by some function closures. I need to copy those functions (since I also ne

3条回答
  •  一整个雨季
    2021-01-15 02:14

    The simple way to make a closure cell would be to make a closure:

    def make_cell(val=None):
        x = val
        def closure():
            return x
        return closure.__closure__[0]
    

    If you want to reassign an existing cell's contents, you'll need to make a C API call:

    import ctypes
    PyCell_Set = ctypes.pythonapi.PyCell_Set
    
    # ctypes.pythonapi functions need to have argtypes and restype set manually
    PyCell_Set.argtypes = (ctypes.py_object, ctypes.py_object)
    
    # restype actually defaults to c_int here, but we might as well be explicit
    PyCell_Set.restype = ctypes.c_int
    
    PyCell_Set(cell, new_value)
    

    CPython only, of course.

提交回复
热议问题