如何创建新的闭包单元对象? [英] How to create new closure cell objects?

查看:83
本文介绍了如何创建新的闭包单元对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要猴子补丁库来替换符号的实例,并且该符号被某些函数闭包引用。我需要复制这些函数(因为我也需要访问该函数的原始未修补版本),但是 __ closure __ 是不可变的,我不能 copy.copy ,那么如何在Python 2.7中创建新的闭包单元对象?

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 need access to original unpatched version of the function as well), but __closure__ is immutable, and I can't copy.copy it, so how can I create new closure cells objects in Python 2.7?

例如,给定此功能

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()

我想看看

0, 42


推荐答案

创建封闭单元格的简单方法是进行封闭:

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]

如果您要重新分配现有单元格的内容,则需要 C API 调用:

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。

CPython only, of course.

这篇关于如何创建新的闭包单元对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆