Extending and Embedding Python, Release 3.9.5 45 2.3. Defining Extension Types: Assorted Topics (continues on next page) (continued from previous page) return -1 ; self->state =0; return 0; } We see above how to call through to the __init__ method of the base type. This pattern is important when writing a type with custom$_{tp_new}$ and$_{tp_dealloc}$ members. The$_{tp_new}$ handler should not actually create the memory for the object with its$_{tp_alloc}$ , but let the base class handle it by calling its own tp_new . The PyTypeObject struct supports a tp_base specifying the type’s concrete base class. Due to cross-platform compiler issues, you can’t fill that field directly with a reference to PyList_Type ; it should be done later in the module initialization function: PyMODINIT_FUNC PyInit_sublist( void ) { PyObject*m; SubListType.tp_base=&PyList_Type; if (PyType_Ready( &SubListType) <0) return NULL ; m =PyModule_Create(&sublistmodule); if (m==NULL ) return NULL ; Py_INCREF(&SubListType); if (PyModule_AddObject(m, "SubList ", (PyObject*)&SubListType) <0) { Py_DECREF( &SubListType); Py_DECREF(m); return NULL ; } return m; } Before calling$_{PyType_Ready()}$ , the type structure must have the$_{tp_base}$ slot filled in. When we are deriving an existing type, it is not necessary to fill out the$_{tp_alloc}$ slot with$_{PyType_GenericNew()}$– the allocation function from the base type will be inherited. After that, calling PyType_Ready() and adding the type object to the module is the same as with the basic $_{Custom}$examples. This section aims to give a quick fly-by on the various type methods you can implement and what they do. Here is the definition of$_{PyTypeObject}$, with some fields only used in debug builds omitted: typedef struct_typeobject { PyObject_VAR_HEAD const char *tp_name; /* For printing, in format "<module>.<name>" */ Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */ /* Methods to implement standard operations */ destructor tp_dealloc; Py_ssize_t tp_vectorcall_offset; getattrfunc tp_getattr; 2.3 Defining Extension Types: Assorted Topics