Skip to content

Latest commit

 

History

History
159 lines (103 loc) · 6.06 KB

gcsupport.rst

File metadata and controls

159 lines (103 loc) · 6.06 KB

c

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 :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:

  1. The memory for the object must be allocated using :cPyObject_GC_New or :cPyObject_GC_NewVar.
  2. Once all the fields which may contain references to other containers are initialized, it must call :cPyObject_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, :cPyObject_GC_UnTrack must be called.
  2. The object's memory must be deallocated using :cPyObject_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.