File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff 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 }));
You can’t perform that action at this time.
0 commit comments