Extending and Embedding Python, Release 3.9.5 Chapter 2. Creating extensions without third party tools 48 If no$_{tp_repr}$handler is specified, the interpreter will supply a representation that uses the type’s$_{tp_name}$ and a uniquely-identifying value for the object. In Python, there are two ways to generate a textual representation of an object: the$_{repr()}$ function, and the$_{str()}$ function. (The$_{print()}$ function just calls$_{str()}$ .) These handlers are both optional. reprfunc tp_repr; reprfunc tp_str; The$_{tp_repr}$handler should return a string object containing a representation of the instance for which it is called. Here is a simple example: static PyObject * newdatatype_repr(newdatatypeobject *obj) { return PyUnicode_FromFormat("Repr-ified_newdatatype{{size:%d}} ", obj->obj_UnderlyingDatatypePtr ->size); } static void my_dealloc(PyObject *obj) { MyObject *self =(MyObject*) obj; PyObject *cbresult; if (self ->my_callback !=NULL ) { PyObject *err_type,*err_value, *err_traceback; /* This saves the current exception state */ PyErr_Fetch(&err_type,&err_value, &err_traceback); cbresult=PyObject_CallNoArgs(self ->my_callback); if (cbresult==NULL ) PyErr_WriteUnraisable(self ->my_callback); else Py_DECREF(cbresult); /* This restores the saved exception state */ PyErr_Restore(err_type, err_value, err_traceback); Py_DECREF(self ->my_callback); } Py_TYPE(obj) ->tp_free((PyObject *)self); } Note: There are limitations to what you can safely do in a deallocator function. First, if your type supports garbage collection (using tp_traverse and/or tp_clear ), some of the object’s members can have been cleared or finalized by the time tp_dealloc is called. Second, in tp_dealloc , your object is in an unstable state: its reference count is equal to zero. Any call to a non-trivial object or API (as in the example above) might end up calling$_{tp_dealloc}$ again, causing a double free and a crash. Starting with Python 3.4, it is recommended not to put any complex finalization code in$_{tp_dealloc}$ , and instead use the new$_{tp_finalize}$type method. See also: PEP 442 explains the new finalization scheme. 2.3.2 Object Presentation