Skip to content

Commit 1827fc3

Browse files
bpo-39778: Add clarification about tp_traverse and ownership (GH-18754)
Automerge-Triggered-By: @pablogsal (cherry picked from commit 6df421f) Co-authored-by: Pablo Galindo <[email protected]>
1 parent 394dc0d commit 1827fc3

File tree

1 file changed

+13
-1
lines changed

1 file changed

+13
-1
lines changed

Doc/c-api/typeobj.rst

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1218,7 +1218,7 @@ and :c:type:`PyType_Type` effectively act as defaults.)
12181218
The :c:member:`~PyTypeObject.tp_traverse` pointer is used by the garbage collector to detect
12191219
reference cycles. A typical implementation of a :c:member:`~PyTypeObject.tp_traverse` function
12201220
simply calls :c:func:`Py_VISIT` on each of the instance's members that are Python
1221-
objects. For example, this is function :c:func:`local_traverse` from the
1221+
objects that the instance owns. For example, this is function :c:func:`local_traverse` from the
12221222
:mod:`_thread` extension module::
12231223

12241224
static int
@@ -1238,6 +1238,18 @@ and :c:type:`PyType_Type` effectively act as defaults.)
12381238
debugging aid you may want to visit it anyway just so the :mod:`gc` module's
12391239
:func:`~gc.get_referents` function will include it.
12401240

1241+
.. warning::
1242+
When implementing :c:member:`~PyTypeObject.tp_traverse`, only the members
1243+
that the instance *owns* (by having strong references to them) must be
1244+
visited. For instance, if an object supports weak references via the
1245+
:c:member:`~PyTypeObject.tp_weaklist` slot, the pointer supporting
1246+
the linked list (what *tp_weaklist* points to) must **not** be
1247+
visited as the instance does not directly own the weak references to itself
1248+
(the weakreference list is there to support the weak reference machinery,
1249+
but the instance has no strong reference to the elements inside it, as they
1250+
are allowed to be removed even if the instance is still alive).
1251+
1252+
12411253
Note that :c:func:`Py_VISIT` requires the *visit* and *arg* parameters to
12421254
:c:func:`local_traverse` to have these specific names; don't name them just
12431255
anything.

0 commit comments

Comments
 (0)