The Python GC API ================= Summary To make a new object participate in garbage collection use PyObject_{New, VarNew, Del} to manage the memory. Set the type flag Py_TPFLAGS_GC and define the type method tp_traverse. You should also add the method tp_clear if your object can create reference cycles (rather than just being part of one). Include PyGC_HEAD_SIZE in the calculation of tp_basicsize. Call PyObject_GC_Init after the pointers followed by tp_traverse become valid (usually just before returning the object from the allocation method. Call PyObject_GC_Fini before those pointers become invalid (usually at the top of the deallocation method). Py_TPFLAGS_GC Objects of a type with this flag set must conform to the rules documented here. For convenience these objects will be referred to as GC objects. PyGC_HEAD_SIZE Extra memory needed for the garbage collector. GC objects must include this in the calculation of their tp_basicsize. If GC is disabled then this is 0. Note that the extra memory is allocated before the PyObject struct. This detail is hidden except when using low level memory management APIs (see below). PyObject_GC_Init(PyObject *op) Add this object to the set of GC objects tracked by the GC. The GC can run at unexpected times so objects must be valid while being tracked by the GC. PyObject_GC_Fini(PyObject *op) Remove this object from the set of GC objects tracked by the GC. Note that PyObject_GC_Init can be called again on this object to add it back to the set of tracked objects. int tp_traverse(PyObject *self, visitproc visit, void *arg) Call visit(reference, arg) on all of this object's references. If visit returns a non-zero value then an error has occurred an that value should be returned immediately. int tp_clear(PyObject *self) Drop references that may have created reference cycles. Immutable objects do not have to define this method since they can never directly create reference cycles. Note that the object must still be valid after calling this method (ie, don't just call Py_DECREF on a reference). The GC will call this method if it detects that this object is involved in a reference cycle. Low level memory management APIs for objects participating in GC: PyGC_Head *PyObject_AS_GC(PyObject *op) Convert a PyObject pointer to a PyGC_Head pointer. PyObject *PyObject_FROM_GC(PyGC_Head *op) Convert a PyGC_Head pointer into a PyObject pointer. void *PyObject_MALLOC(int n) void *PyObject_REALLOC(void *gc, int n) void PyObject_DEL(void *gc) void PyObject_FREE(void *gc) For objects participating in GC, these macros deal with PyGC_Head pointers. The PyObject_FROM_GC and PyObject_AS_GC macros should be used to convert back and forth.