c
Python's support for detecting and collecting garbage which involves circular references requires support from object types which are "containers" for other objects which may also be containers. Types which do not store references to other objects, or which only store references to atomic types (such as numbers or strings), do not need to provide any explicit support for garbage collection.
To create a container type, the :c~PyTypeObject.tp_flags
field of the type object must include the Py_TPFLAGS_HAVE_GC
and provide an implementation of the :c~PyTypeObject.tp_traverse
handler. If instances of the type are mutable, a :c~PyTypeObject.tp_clear
implementation must also be provided.
Py_TPFLAGS_HAVE_GC
Objects with a type with this flag set must conform with the rules documented here. For convenience these objects will be referred to as container objects.
Constructors for container types must conform to two rules:
- The memory for the object must be allocated using :c
PyObject_GC_New
or :cPyObject_GC_NewVar
. - Once all the fields which may contain references to other containers are initialized, it must call :c
PyObject_GC_Track
.
Similarly, the deallocator for the object must conform to a similar pair of rules:
- Before fields which refer to other containers are invalidated, :c
PyObject_GC_UnTrack
must be called. - The object's memory must be deallocated using :c
PyObject_GC_Del
.
The :c~PyTypeObject.tp_traverse
handler accepts a function parameter of this type:
The :c~PyTypeObject.tp_traverse
handler must have the following type:
To simplify writing :c~PyTypeObject.tp_traverse
handlers, a :cPy_VISIT
macro is provided. In order to use this macro, the :c~PyTypeObject.tp_traverse
implementation must name its arguments exactly visit and arg:
The :c~PyTypeObject.tp_clear
handler must be of the :cinquiry
type, or NULL
if the object is immutable.