Skip to content

Commit ad587eb

Browse files
committed
Update docs for pybind11::custom_type_setup
1 parent 40b9586 commit ad587eb

1 file changed

Lines changed: 12 additions & 4 deletions

File tree

docs/advanced/classes.rst

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1384,13 +1384,21 @@ You can do that using ``py::custom_type_setup``:
13841384
auto *type = &heap_type->ht_type;
13851385
type->tp_flags |= Py_TPFLAGS_HAVE_GC;
13861386
type->tp_traverse = [](PyObject *self_base, visitproc visit, void *arg) {
1387-
auto &self = py::cast<OwnsPythonObjects&>(py::handle(self_base));
1388-
Py_VISIT(self.value.ptr());
1387+
// https://docs.python.org/3/c-api/typeobj.html#c.PyTypeObject.tp_traverse
1388+
#if PY_VERSION_HEX >= 0x03090000 // Python 3.9
1389+
Py_VISIT(Py_TYPE(self_base));
1390+
#endif
1391+
if (py::detail::is_holder_constructed(self_base)) {
1392+
auto &self = py::cast<OwnsPythonObjects&>(py::handle(self_base));
1393+
Py_VISIT(self.value.ptr());
1394+
}
13891395
return 0;
13901396
};
13911397
type->tp_clear = [](PyObject *self_base) {
1392-
auto &self = py::cast<OwnsPythonObjects&>(py::handle(self_base));
1393-
self.value = py::none();
1398+
if (py::detail::is_holder_constructed(self_base)) {
1399+
auto &self = py::cast<OwnsPythonObjects&>(py::handle(self_base));
1400+
self.value = py::none();
1401+
}
13941402
return 0;
13951403
};
13961404
}));

0 commit comments

Comments
 (0)