Weak Reference Objects

Python supportsweak references as first-class objects. There are twospecific object types which directly implement weak references. The first is asimple reference object, and the second acts as a proxy for the original objectas much as it can.

intPyWeakref_Check(PyObject*ob)

Return true ifob is either a reference or proxy object. This functionalways succeeds.

intPyWeakref_CheckRef(PyObject*ob)

Return true ifob is a reference object. This function always succeeds.

intPyWeakref_CheckProxy(PyObject*ob)

Return true ifob is a proxy object. This function always succeeds.

PyObject*PyWeakref_NewRef(PyObject*ob,PyObject*callback)
Return value: New reference. Part of theStable ABI.

Return a weak reference object for the objectob. This will always returna new reference, but is not guaranteed to create a new object; an existingreference object may be returned. The second parameter,callback, can be acallable object that receives notification whenob is garbage collected; itshould accept a single parameter, which will be the weak reference objectitself.callback may also beNone orNULL. Ifob is not aweakly referencable object, or ifcallback is not callable,None, orNULL, this will returnNULL and raiseTypeError.

PyObject*PyWeakref_NewProxy(PyObject*ob,PyObject*callback)
Return value: New reference. Part of theStable ABI.

Return a weak reference proxy object for the objectob. This will alwaysreturn a new reference, but is not guaranteed to create a new object; anexisting proxy object may be returned. The second parameter,callback, canbe a callable object that receives notification whenob is garbagecollected; it should accept a single parameter, which will be the weakreference object itself.callback may also beNone orNULL. Ifobis not a weakly referencable object, or ifcallback is not callable,None, orNULL, this will returnNULL and raiseTypeError.

PyObject*PyWeakref_GetObject(PyObject*ref)
Return value: Borrowed reference. Part of theStable ABI.

Return the referenced object from a weak reference,ref. If the referent isno longer live, returnsPy_None.

Note

This function returns aborrowed reference to the referenced object.This means that you should always callPy_INCREF() on the objectexcept when it cannot be destroyed before the last usage of the borrowedreference.

PyObject*PyWeakref_GET_OBJECT(PyObject*ref)
Return value: Borrowed reference.

Similar toPyWeakref_GetObject(), but does no error checking.

voidPyObject_ClearWeakRefs(PyObject*object)
Part of theStable ABI.

This function is called by thetp_dealloc handlerto clear weak references.

This iterates through the weak references forobject and calls callbacksfor those references which have one. It returns when all callbacks havebeen attempted.