From c390756e7bd76fc32f637928e6ea711b58d3a7d9 Mon Sep 17 00:00:00 2001 From: Sam Gross Date: Thu, 4 Dec 2025 16:37:50 -0500 Subject: [PATCH] gh-123241: Document restrictions for tp_traverse implementations --- Doc/c-api/gcsupport.rst | 4 ++++ Doc/c-api/typeobj.rst | 5 +++++ 2 files changed, 9 insertions(+) diff --git a/Doc/c-api/gcsupport.rst b/Doc/c-api/gcsupport.rst index f6fa52b36c5ab3..fed795b1e8c963 100644 --- a/Doc/c-api/gcsupport.rst +++ b/Doc/c-api/gcsupport.rst @@ -232,6 +232,10 @@ The :c:member:`~PyTypeObject.tp_traverse` handler must have the following type: object argument. If *visit* returns a non-zero value that value should be returned immediately. + The traversal function must not have any side effects. Implementations + may not modify the reference counts of any Python objects nor create or + destroy any Python objects. + To simplify writing :c:member:`~PyTypeObject.tp_traverse` handlers, a :c:func:`Py_VISIT` macro is provided. In order to use this macro, the :c:member:`~PyTypeObject.tp_traverse` implementation must name its arguments exactly *visit* and *arg*: diff --git a/Doc/c-api/typeobj.rst b/Doc/c-api/typeobj.rst index 49fe02d919df8b..efac86078f9af5 100644 --- a/Doc/c-api/typeobj.rst +++ b/Doc/c-api/typeobj.rst @@ -1569,6 +1569,11 @@ and :c:data:`PyType_Type` effectively act as defaults.) but the instance has no strong reference to the elements inside it, as they are allowed to be removed even if the instance is still alive). + .. warning:: + The traversal function must not have any side effects. It must not + modify the reference counts of any Python objects nor create or destroy + any Python objects. + Note that :c:func:`Py_VISIT` requires the *visit* and *arg* parameters to :c:func:`!local_traverse` to have these specific names; don't name them just anything.