Extending and Embedding Python, Release 3.9.5 (continued from previous page) Chapter 2. Creating extensions without third party tools 44 (continues on next page) The primary difference for derived type objects is that the base type’s object structure must be the first value. The base type will already include the$_{PyObject_HEAD()}$ at the beginning of its structure. When a Python object is a$_{SubList}$ instance, its$_{PyObject *}$ pointer can be safely cast to both$_{PyListObject}$ $_{*}$and$_{SubListObject *}$ : static int SubList_init(SubListObject*self, PyObject*args, PyObject*kwds) { if (PyList_Type.tp_init((PyObject *) self, args, kwds) <0) typedef struct { PyListObject list; int state; } SubListObject; As you can see, the source code closely resembles the$_{Custom}$examples in previous sections. We will break down the main differences between them. return 0; } static PyTypeObject SubListType ={ PyVarObject_HEAD_INIT(NULL ,0) .tp_name ="sublist.SubList", .tp_doc="SubList objects", .tp_basicsize= sizeof (SubListObject), .tp_itemsize=0, .tp_flags =Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, .tp_init=(initproc) SubList_init, .tp_methods=SubList_methods, }; static PyModuleDef sublistmodule={ PyModuleDef_HEAD_INIT, .m_name="sublist", .m_doc="Example module that creates an extension type. ", .m_size=-1 , }; 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; }