Skip to content

Commit dce1fcb

Browse files
committed
fix: use PyUnstable_IsImmortal
Signed-off-by: Henry Schreiner <[email protected]>
1 parent 8031427 commit dce1fcb

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

tests/pybind11_tests.cpp

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,15 @@ const char *cpp_std() {
7575
#endif
7676
}
7777

78+
bool is_immortal(py::handle object) {
79+
// If Python doesn't support immortal objects, this returns False
80+
#if PY_VERSION_HEX >= 0x030E0000
81+
return PyUnstable_IsImmortal(object.ptr()) != 0;
82+
#else
83+
return Py_REFCNT(object.ptr()) == UINT32_MAX;
84+
#endif
85+
}
86+
7887
PYBIND11_MODULE(pybind11_tests, m, py::mod_gil_not_used()) {
7988
m.doc() = "pybind11 test module";
8089

@@ -90,7 +99,6 @@ PYBIND11_MODULE(pybind11_tests, m, py::mod_gil_not_used()) {
9099
m.attr("cpp_std") = cpp_std();
91100
m.attr("PYBIND11_INTERNALS_ID") = PYBIND11_INTERNALS_ID;
92101
// Free threaded Python uses UINT32_MAX for immortal objects.
93-
m.attr("PYBIND11_REFCNT_IMMORTAL") = UINT32_MAX;
94102
m.attr("PYBIND11_SIMPLE_GIL_MANAGEMENT") =
95103
#if defined(PYBIND11_SIMPLE_GIL_MANAGEMENT)
96104
true;
@@ -106,6 +114,8 @@ PYBIND11_MODULE(pybind11_tests, m, py::mod_gil_not_used()) {
106114
m.attr("detailed_error_messages_enabled") = false;
107115
#endif
108116

117+
m.def("is_immortal", &is_immortal, "Returns true if Python supports it and the object is immortal");
118+
109119
py::class_<UserType>(m, "UserType", "A `py::class_` type for testing")
110120
.def(py::init<>())
111121
.def(py::init<int>())

tests/test_class.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import pytest
77

88
import env
9-
from pybind11_tests import PYBIND11_REFCNT_IMMORTAL, ConstructorStats, UserType
9+
from pybind11_tests import is_immortal, ConstructorStats, UserType
1010
from pybind11_tests import class_ as m
1111

1212

@@ -398,7 +398,7 @@ class PyDog(m.Dog):
398398

399399
assert refcount_1 == refcount_3
400400
assert (refcount_2 > refcount_1) or (
401-
refcount_2 == refcount_1 == PYBIND11_REFCNT_IMMORTAL
401+
is_immortal(refcount_2) and is_immortal(refcount_1)
402402
)
403403

404404

0 commit comments

Comments
 (0)