Skip to content

Commit 72fff60

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 499c926 commit 72fff60

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
@@ -496,7 +496,7 @@ type objects) *must* have the :attr:`ob_size` field.
496496
The :c:member:`~PyTypeObject.tp_traverse` pointer is used by the garbage collector to detect
497497
reference cycles. A typical implementation of a :c:member:`~PyTypeObject.tp_traverse` function
498498
simply calls :c:func:`Py_VISIT` on each of the instance's members that are Python
499-
objects. For example, this is function :c:func:`local_traverse` from the
499+
objects that the instance owns. For example, this is function :c:func:`local_traverse` from the
500500
:mod:`_thread` extension module::
501501

502502
static int
@@ -516,6 +516,18 @@ type objects) *must* have the :attr:`ob_size` field.
516516
debugging aid you may want to visit it anyway just so the :mod:`gc` module's
517517
:func:`~gc.get_referents` function will include it.
518518

519+
.. warning::
520+
When implementing :c:member:`~PyTypeObject.tp_traverse`, only the members
521+
that the instance *owns* (by having strong references to them) must be
522+
visited. For instance, if an object supports weak references via the
523+
:c:member:`~PyTypeObject.tp_weaklist` slot, the pointer supporting
524+
the linked list (what *tp_weaklist* points to) must **not** be
525+
visited as the instance does not directly own the weak references to itself
526+
(the weakreference list is there to support the weak reference machinery,
527+
but the instance has no strong reference to the elements inside it, as they
528+
are allowed to be removed even if the instance is still alive).
529+
530+
519531
Note that :c:func:`Py_VISIT` requires the *visit* and *arg* parameters to
520532
:c:func:`local_traverse` to have these specific names; don't name them just
521533
anything.

0 commit comments

Comments
 (0)