Supporting Cyclic Garbage Collection¶
Python’s support for detecting and collecting garbage which involves circularreferences requires support from object types which are “containers” for otherobjects which may also be containers. Types which do not store references toother objects, or which only store references to atomic types (such as numbersor strings), do not need to provide any explicit support for garbagecollection.
To create a container type, thetp_flags field of the type object mustinclude thePy_TPFLAGS_HAVE_GC and provide an implementation of thetp_traverse handler. If instances of the type are mutable, atp_clear implementation must also be provided.
Py_TPFLAGS_HAVE_GCObjects with a type with this flag set must conform with the rulesdocumented here. For convenience these objects will be referred to ascontainer objects.
Constructors for container types must conform to two rules:
The memory for the object must be allocated using
PyObject_GC_New()orPyObject_GC_NewVar().Once all the fields which may contain references to other containers areinitialized, it must call
PyObject_GC_Track().
Similarly, the deallocator for the object must conform to a similar pair ofrules:
Before fields which refer to other containers are invalidated,
PyObject_GC_UnTrack()must be called.The object’s memory must be deallocated using
PyObject_GC_Del().Warning
If a type adds the Py_TPFLAGS_HAVE_GC, then itmust implement at leasta
tp_traversehandler or explicitly use onefrom its subclass or subclasses.When calling
PyType_Ready()or some of the APIs that indirectlycall it likePyType_FromSpecWithBases()orPyType_FromSpec()the interpreter will automatically populate thetp_flags,tp_traverseandtp_clearfields if the type inherits from aclass that implements the garbage collector protocol and the child classdoesnot include thePy_TPFLAGS_HAVE_GCflag.
- TYPE*
PyObject_GC_New(TYPE,PyTypeObject *type)¶ Analogous to
PyObject_New()but for container objects with thePy_TPFLAGS_HAVE_GCflag set.
- TYPE*
PyObject_GC_NewVar(TYPE,PyTypeObject *type,Py_ssize_t size)¶ Analogous to
PyObject_NewVar()but for container objects with thePy_TPFLAGS_HAVE_GCflag set.
- TYPE*
PyObject_GC_Resize(TYPE,PyVarObject *op,Py_ssize_t newsize)¶ Resize an object allocated by
PyObject_NewVar(). Returns theresized object orNULLon failure.op must not be tracked by the collector yet.
- void
PyObject_GC_Track(PyObject *op)¶ Adds the objectop to the set of container objects tracked by thecollector. The collector can run at unexpected times so objects must bevalid while being tracked. This should be called once all the fieldsfollowed by the
tp_traversehandler become valid, usually near theend of the constructor.
- int
PyObject_IS_GC(PyObject *obj)¶ Returns non-zero if the object implements the garbage collector protocol,otherwise returns 0.
The object cannot be tracked by the garbage collector if this function returns 0.
- int
PyObject_GC_IsTracked(PyObject *op)¶ Returns 1 if the object type ofop implements the GC protocol andop is beingcurrently tracked by the garbage collector and 0 otherwise.
This is analogous to the Python function
gc.is_tracked().New in version 3.9.
- int
PyObject_GC_IsFinalized(PyObject *op)¶ Returns 1 if the object type ofop implements the GC protocol andop has beenalready finalized by the garbage collector and 0 otherwise.
This is analogous to the Python function
gc.is_finalized().New in version 3.9.
- void
PyObject_GC_Del(void *op)¶ Releases memory allocated to an object using
PyObject_GC_New()orPyObject_GC_NewVar().
- void
PyObject_GC_UnTrack(void *op)¶ Remove the objectop from the set of container objects tracked by thecollector. Note that
PyObject_GC_Track()can be called again onthis object to add it back to the set of tracked objects. The deallocator(tp_deallochandler) should call this for the object before any ofthe fields used by thetp_traversehandler become invalid.
Changed in version 3.8:The_PyObject_GC_TRACK() and_PyObject_GC_UNTRACK() macroshave been removed from the public C API.
Thetp_traverse handler accepts a function parameter of this type:
- int
(*visitproc)(PyObject *object, void *arg)¶ Type of the visitor function passed to the
tp_traversehandler.The function should be called with an object to traverse asobject andthe third parameter to thetp_traversehandler asarg. ThePython core uses several visitor functions to implement cyclic garbagedetection; it’s not expected that users will need to write their ownvisitor functions.
Thetp_traverse handler must have the following type:
- int
(*traverseproc)(PyObject *self,visitproc visit, void *arg)¶ Traversal function for a container object. Implementations must call thevisit function for each object directly contained byself, with theparameters tovisit being the contained object and thearg value passedto the handler. Thevisit function must not be called with a
NULLobject argument. Ifvisit returns a non-zero value that value should bereturned immediately.
To simplify writingtp_traverse handlers, aPy_VISIT() macro isprovided. In order to use this macro, thetp_traverse implementationmust name its arguments exactlyvisit andarg:
- void
Py_VISIT(PyObject *o)¶ Ifo is not
NULL, call thevisit callback, with argumentsoandarg. Ifvisit returns a non-zero value, then return it.Using this macro,tp_traversehandlerslook like:staticintmy_traverse(Noddy*self,visitprocvisit,void*arg){Py_VISIT(self->foo);Py_VISIT(self->bar);return0;}
Thetp_clear handler must be of theinquiry type, orNULLif the object is immutable.
- int
(*inquiry)(PyObject *self)¶ Drop references that may have created reference cycles. Immutable objectsdo not have to define this method since they can never directly createreference cycles. Note that the object must still be valid after callingthis method (don’t just call
Py_DECREF()on a reference). Thecollector will call this method if it detects that this object is involvedin a reference cycle.