PyObject_GC_UnTrack(self); Custom_clear(self); Py_TYPE(self) ->tp_free((PyObject *) self); } 

Finally, we add the Py_TPFLAGS_HAVE_GC flag to the class flags: 

(continued from previous page) 

.tp_flags =Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, 

That’s pretty much it. If we had written custom$_{tp_alloc}$ or$_{tp_free}$handlers, we’d need to modify them for cyclic garbage collection. Most extensions will use the versions automatically provided. 

## 2.2.5 Subclassing other types 

It is possible to create new extension types that are derived from existing types. It is easiest to inherit from the built in types, since an extension can easily use the $_{PyTypeObject}$it needs. It can be difficult to share these $_{PyTypeObject}$structures between extension modules. 

In this example we will create a SubList type that inherits from the built-in $_{list}$type. The new type will be completely compatible with regular lists, but will have an additional$_{increment()}$ method that increases an internal counter: 

>>> import sublist >>> s =sublist.SubList(range(3)) >>> s.extend(s) >>> print(len(s)) 6 >>> print(s.increment()) 1 >>> print(s.increment()) 2 

#define PY_SSIZE_T_CLEAN #include<Python.h> typedef struct { PyListObject list; int state; } SubListObject; static PyObject * SubList_increment(SubListObject*self, PyObject*unused) { self->state++; return PyLong_FromLong(self ->state); } static PyMethodDef SubList_methods[] ={ { "increment", (PyCFunction) SubList_increment, METH_NOARGS, PyDoc_STR( "increment state counter ")}, { NULL }, }; static int SubList_init(SubListObject*self, PyObject*args, PyObject*kwds) { if (PyList_Type.tp_init((PyObject *) self, args, kwds) <0) return -1 ; self->state =0; 

(continues on next page) 

