弱引用对象¶
Python 支持“弱引用”作为一类对象。具体来说,有两种直接实现弱引用的对象。第一种就是简单的引用对象,第二种尽可能地作用为一个原对象的代理。
-
PyObject *PyWeakref_NewRef(PyObject *ob, PyObject *callback)¶
- 返回值:新的引用。 属于 稳定 ABI.
Return a weak reference object for the object ob. This will always return a new reference, but is not guaranteed to create a new object; an existing reference object may be returned. The second parameter, callback, can be a callable object that receives notification when ob is garbage collected; it should accept a single parameter, which will be the weak reference object itself. callback may also be
NoneorNULL. If ob is not a weakly referenceable object, or if callback is not callable,None, orNULL, this will raiseTypeErrorand returnNULL.在 3.16.0a0 (unreleased) 版本发生变更: Raise
TypeErrorif callback is not callable,None, orNULL.参见
PyType_SUPPORTS_WEAKREFS()用于检测 ob 是否可被弱引用。
-
PyObject *PyWeakref_NewProxy(PyObject *ob, PyObject *callback)¶
- 返回值:新的引用。 属于 稳定 ABI.
Return a weak reference proxy object for the object ob. This will always return a new reference, but is not guaranteed to create a new object; an existing proxy object may be returned. The second parameter, callback, can be a callable object that receives notification when ob is garbage collected; it should accept a single parameter, which will be the weak reference object itself. callback may also be
NoneorNULL. If ob is not a weakly referenceable object, or if callback is not callable,NULL, this will raiseTypeErrorand returnNULL.在 3.16.0a0 (unreleased) 版本发生变更: Raise
TypeErrorif callback is not callable,None, orNULL.参见
PyType_SUPPORTS_WEAKREFS()用于检测 ob 是否可被弱引用。
-
int PyWeakref_GetRef(PyObject *ref, PyObject **pobj)¶
- 属于 稳定 ABI 自 3.13 版起.
基于一个弱引用 ref 获取一个指向被引用对象的 strong reference 存入到 *pobj。
成功时,将 *pobj 设为一个新的指向被引用对象的 strong reference 并返回 1。
如果引用不可用,则将 *pobj 设为
NULL并返回 0。发生错误时,将引发异常并返回 -1。
Added in version 3.13.
-
int PyWeakref_IsDead(PyObject *ref)¶
测试弱引用 ref 是否已死亡。如果该引用已死亡则返回 1,如果仍存活则返回 0,如果 ref 不是弱引用对象则返回 -1 并设置一个错误。
Added in version 3.14.
-
void PyObject_ClearWeakRefs(PyObject *object)¶
- 属于 稳定 ABI.
此函数将被
tp_dealloc处理器调用以清空弱引用。此函数将迭代 object 的弱引用并调用这些引用中可能存在的回调。它将在尝试了所有回调之后返回。
-
void PyUnstable_Object_ClearWeakRefsNoCallbacks(PyObject *object)¶
- 这是 不稳定 API。它可能在次要版本中不经警告地被更改。
清空 object 的弱引用而不调用回调。
此函数将由
tp_dealloc处理器针对带有终结器 (即__del__()) 的类型进行调用。针对这些对象的处理器会先调用PyObject_ClearWeakRefs()来清空弱引用并调用其回调,然后调用终结器,最后调用此函数来清空终结器可能创建的任何弱引用。在大多数情况下,更适当的做法是使用
PyObject_ClearWeakRefs()而不是此函数来清空弱引用。Added in version 3.13.