Skip to content

Commit 8b55bc3

Browse files
authored
bpo-44263: Better explain the GC contract for PyType_FromSpecWithBases (GH-26442)
1 parent de14d70 commit 8b55bc3

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

Doc/c-api/gcsupport.rst

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,17 @@ Constructors for container types must conform to two rules:
3333
#. Once all the fields which may contain references to other containers are
3434
initialized, it must call :c:func:`PyObject_GC_Track`.
3535

36+
.. warning::
37+
If a type adds the Py_TPFLAGS_HAVE_GC, then it *must* implement at least
38+
a :c:member:`~PyTypeObject.tp_traverse` handler or explicitly use one
39+
from its subclass or subclasses.
40+
41+
Some APIs like :c:func:`PyType_FromSpecWithBases` or
42+
:c:func:`PyType_FromSpec` will automatically populate the
43+
:c:member:`~PyTypeObject.tp_flags`, :c:member:`~PyTypeObject.tp_traverse`
44+
and :c:member:`~PyTypeObject.tp_clear` fields if the type inherits from a
45+
class that implements the garbage collector protocol and the child class
46+
does *not* include the :const:`Py_TPFLAGS_HAVE_GC` flag.
3647

3748
.. c:function:: TYPE* PyObject_GC_New(TYPE, PyTypeObject *type)
3849

Doc/c-api/type.rst

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,13 @@ The following functions and structs are used to create
169169
The associated module is not inherited by subclasses; it must be specified
170170
for each class individually.
171171
172+
If some of the bases in *bases* implements the GC protocol and the type being
173+
created does not include the :const:`Py_TPFLAGS_HAVE_GC` in the flags included in
174+
*spec*, then the GC protocol will be automatically implemented from its parents. On
175+
the contrary, if the type being created does include :const:`Py_TPFLAGS_HAVE_GC` in
176+
its flags then it *must* implement the GC protocol itself by at least including a slot
177+
for :c:member:`~PyTypeObject.tp_traverse` in *spec*.
178+
172179
This function calls :c:func:`PyType_Ready` on the new type.
173180
174181
.. versionadded:: 3.9

0 commit comments

Comments
 (0)