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.
- int
PyWeakref_Check(ob)¶ Return true ifob is either a reference or proxy object. This functionalways succeeds.
- int
PyWeakref_CheckRef(ob)¶ Return true ifob is a reference object. This function always succeeds.
- int
PyWeakref_CheckProxy(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 be
NoneorNULL. Ifob is not aweakly referencable object, or ifcallback is not callable,None, orNULL, this will returnNULLand 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 be
NoneorNULL. Ifobis not a weakly referencable object, or ifcallback is not callable,None, orNULL, this will returnNULLand 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, returns
Py_None.Note
This function returns aborrowed reference to the referenced object.This means that you should always call
Py_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 to
PyWeakref_GetObject(), but implemented as a macro that does noerror checking.
- void
PyObject_ClearWeakRefs(PyObject *object)¶ - Part of theStable ABI.
This function is called by the
tp_deallochandlerto 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.