Skip to content

Commit 6df421f

Browse files
authored
bpo-39778: Add clarification about tp_traverse and ownership (GH-18754)
Automerge-Triggered-By: @pablogsal
1 parent 4991cf4 commit 6df421f

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
@@ -1192,7 +1192,7 @@ and :c:type:`PyType_Type` effectively act as defaults.)
11921192
The :c:member:`~PyTypeObject.tp_traverse` pointer is used by the garbage collector to detect
11931193
reference cycles. A typical implementation of a :c:member:`~PyTypeObject.tp_traverse` function
11941194
simply calls :c:func:`Py_VISIT` on each of the instance's members that are Python
1195-
objects. For example, this is function :c:func:`local_traverse` from the
1195+
objects that the instance owns. For example, this is function :c:func:`local_traverse` from the
11961196
:mod:`_thread` extension module::
11971197

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

1215+
.. warning::
1216+
When implementing :c:member:`~PyTypeObject.tp_traverse`, only the members
1217+
that the instance *owns* (by having strong references to them) must be
1218+
visited. For instance, if an object supports weak references via the
1219+
:c:member:`~PyTypeObject.tp_weaklist` slot, the pointer supporting
1220+
the linked list (what *tp_weaklist* points to) must **not** be
1221+
visited as the instance does not directly own the weak references to itself
1222+
(the weakreference list is there to support the weak reference machinery,
1223+
but the instance has no strong reference to the elements inside it, as they
1224+
are allowed to be removed even if the instance is still alive).
1225+
1226+
12151227
Note that :c:func:`Py_VISIT` requires the *visit* and *arg* parameters to
12161228
:c:func:`local_traverse` to have these specific names; don't name them just
12171229
anything.

0 commit comments

Comments
 (0)