Skip to content

Commit

Permalink
fix tp_traverse, add note to docs
Browse files Browse the repository at this point in the history
  • Loading branch information
wjakob committed Aug 22, 2024
1 parent 93a39a7 commit 037765f
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
21 changes: 20 additions & 1 deletion docs/typeslots.rst
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ reference cycles:
// If w->value has an associated CPython object, return it.
// If not, value.ptr() will equal NULL, which is also fine.
nb::object value = nb::find(w->value);
nb::handle value = nb::find(w->value);
// Inform the Python GC about the instance (if non-NULL)
Py_VISIT(value.ptr());
Expand All @@ -149,6 +149,25 @@ reference cycles:
The type ``visitproc`` and macro ``Py_VISIT()`` are part of the Python C API.

.. note::

When targeting free-threaded Python, it is important that the ``tp_traverse``
callback does not hold additional references to the objects being traversed.

A previous version of this documentation page suggested the following

.. code-block:: cpp
nb::object value = nb::find(w->value);
Py_VISIT(value.ptr());
However, these now have to change to

.. code-block:: cpp
nb::handle value = nb::find(w->value);
Py_VISIT(value.ptr());
The expression :cpp:func:`nb::inst_ptr\<Wrapper\>(self) <inst_ptr>` efficiently
returns the C++ instance associated with a Python object and is explained in
the documentation about nanobind's :cpp:ref:`low level interface <lowlevel>`.
Expand Down
2 changes: 1 addition & 1 deletion tests/test_classes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ int wrapper_tp_traverse(PyObject *self, visitproc visit, void *arg) {
Wrapper *w = nb::inst_ptr<Wrapper>(self);

// If c->value corresponds to an associated CPython object, return it
nb::object value = nb::find(w->value);
nb::handle value = nb::find(w->value);

// Inform the Python GC about it
Py_VISIT(value.ptr());
Expand Down
2 changes: 1 addition & 1 deletion tests/test_stl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ struct FuncWrapper {
int funcwrapper_tp_traverse(PyObject *self, visitproc visit, void *arg) {
FuncWrapper *w = nb::inst_ptr<FuncWrapper>(self);

nb::object f = nb::cast(w->f, nb::rv_policy::none);
nb::handle f = nb::cast(w->f, nb::rv_policy::none);
Py_VISIT(f.ptr());

#if PY_VERSION_HEX >= 0x03090000
Expand Down

0 comments on commit 037765f

Please sign in to comment.