@@ -654,16 +654,31 @@ and :c:type:`PyType_Type` effectively act as defaults.)
654
654
the instance is still in existence, but there are no references to it. The
655
655
destructor function should free all references which the instance owns, free all
656
656
memory buffers owned by the instance (using the freeing function corresponding
657
- to the allocation function used to allocate the buffer), and finally (as its
658
- last action) call the type's :c:member: `~PyTypeObject.tp_free ` function. If the type is not
659
- subtypable (doesn't have the :const: `Py_TPFLAGS_BASETYPE ` flag bit set), it is
657
+ to the allocation function used to allocate the buffer), and call the type's
658
+ :c:member: `~PyTypeObject.tp_free ` function. If the type is not subtypable
659
+ (doesn't have the :const: `Py_TPFLAGS_BASETYPE ` flag bit set), it is
660
660
permissible to call the object deallocator directly instead of via
661
661
:c:member: `~PyTypeObject.tp_free `. The object deallocator should be the one used to allocate the
662
662
instance; this is normally :c:func: `PyObject_Del ` if the instance was allocated
663
663
using :c:func: `PyObject_New ` or :c:func: `PyObject_VarNew `, or
664
664
:c:func: `PyObject_GC_Del ` if the instance was allocated using
665
665
:c:func: `PyObject_GC_New ` or :c:func: `PyObject_GC_NewVar `.
666
666
667
+ Finally, if the type is heap allocated (:const: `Py_TPFLAGS_HEAPTYPE `), the
668
+ deallocator should decrement the reference count for its type object after
669
+ calling the type deallocator. In order to avoid dangling pointers, the
670
+ recommended way to achieve this is:
671
+
672
+ .. code-block :: c
673
+
674
+ static void foo_dealloc(foo_object *self) {
675
+ PyTypeObject *tp = Py_TYPE(self);
676
+ // free references and buffers here
677
+ tp->tp_free(self);
678
+ Py_DECREF(tp);
679
+ }
680
+
681
+
667
682
**Inheritance: **
668
683
669
684
This field is inherited by subtypes.
@@ -1021,7 +1036,8 @@ and :c:type:`PyType_Type` effectively act as defaults.)
1021
1036
1022
1037
.. data :: Py_TPFLAGS_HEAPTYPE
1023
1038
1024
- This bit is set when the type object itself is allocated on the heap. In this
1039
+ This bit is set when the type object itself is allocated on the heap, for
1040
+ example, types created dynamically using :c:func: `PyType_FromSpec `. In this
1025
1041
case, the :attr: `ob_type ` field of its instances is considered a reference to
1026
1042
the type, and the type object is INCREF'ed when a new instance is created, and
1027
1043
DECREF'ed when an instance is destroyed (this does not apply to instances of
0 commit comments