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 tp_flags field of the type object must include the Py_TPFLAGS_HAVE_GC and provide an implementation of the tp_traverse handler. If instances of the type are mutable, a tp_clear implementation must also be provided.
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:
Similarly, the deallocator for the object must conform to a similar pair of rules:
The tp_traverse handler accepts a function parameter of this type:
The tp_traverse handler must have the following type:
To simplify writing tp_traverse handlers, a :cfunc:`Py_VISIT` macro is provided. In order to use this macro, the tp_traverse implementation must name its arguments exactly visit and arg:
The tp_clear handler must be of the :ctype:`inquiry` type, or NULL if the object is immutable.