Extending and Embedding Python, Release 3.9.5 2.2. Defining Extension Types: Tutorial 43 (continues on next page) (continued from previous page) PyObject_GC_UnTrack(self); Custom_clear(self); Py_TYPE(self) ->tp_free((PyObject *) self); } >>> 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; 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: 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. 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 Finally, we add the Py_TPFLAGS_HAVE_GC flag to the class flags: .tp_flags =Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,