如何让 Python 解释器“忘记”Cython 中的变量?

问题描述 投票:0回答:1

假设我有这个 Cython 课程,如下所示:

cdef class MyClass:
    cdef readonly object _value
    def __cinit__(self, value):
        self._value = value

    cpdef forget_self(self):
        # what should I write here?

Python 中所需的行为应该如下所示:

>>> my_class = MyClass(5)
>>> my_class._value
... 5
>>> my_class.forget_self()
>>> my_class
... # NameError raised here

我看到了

_Py_ForgetReference
https://github.com/python/cpython/blob/33838fedf7ed6ee907a49d042f8fa123178a1f9c/Objects/object.c#L2226),但只有当
#ifdef Py_TRACE_REFS
被激活时它才会被激活。

如果提高

NameError
不可能,那么我希望
MyClass.forget_self()
设置
self
,即将
MyClass
None
的对象,会
Py_SETREF
https://github.com) /python/cpython/blob/main/Include/cpython/object.h#L326)就足够了吗?

python cython cpython
1个回答
0
投票

这是不可能的。 Python 引用不是这样工作的。

© www.soinside.com 2019 - 2024. All rights reserved.