Source

sandbox/morph / Doc / c-api / gcsupport.rst

Full commit

Supporting Cyclic Garbage Collection

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 :attr:`tp_flags` field of the type object must include the :const:`Py_TPFLAGS_HAVE_GC` and provide an implementation of the :attr:`tp_traverse` handler. If instances of the type are mutable, a :attr:`tp_clear` implementation must also be provided.

Constructors for container types must conform to two rules:

  1. The memory for the object must be allocated using :c:func:`PyObject_GC_New` or :c:func:`PyObject_GC_NewVar`.
  2. Once all the fields which may contain references to other containers are initialized, it must call :c:func:`PyObject_GC_Track`.

Similarly, the deallocator for the object must conform to a similar pair of rules:

  1. Before fields which refer to other containers are invalidated, :c:func:`PyObject_GC_UnTrack` must be called.
  2. The object's memory must be deallocated using :c:func:`PyObject_GC_Del`.

The :attr:`tp_traverse` handler accepts a function parameter of this type:

The :attr:`tp_traverse` handler must have the following type:

To simplify writing :attr:`tp_traverse` handlers, a :c:func:`Py_VISIT` macro is provided. In order to use this macro, the :attr:`tp_traverse` implementation must name its arguments exactly visit and arg:

The :attr:`tp_clear` handler must be of the :c:type:`inquiry` type, or NULL if the object is immutable.