Skip to content

Commit e7a623e

Browse files
committed
fix: use sys._is_immortal
Signed-off-by: Henry Schreiner <[email protected]>
1 parent dce1fcb commit e7a623e

File tree

2 files changed

+13
-19
lines changed

2 files changed

+13
-19
lines changed

tests/pybind11_tests.cpp

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -75,15 +75,6 @@ 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-
8778
PYBIND11_MODULE(pybind11_tests, m, py::mod_gil_not_used()) {
8879
m.doc() = "pybind11 test module";
8980

@@ -114,8 +105,6 @@ PYBIND11_MODULE(pybind11_tests, m, py::mod_gil_not_used()) {
114105
m.attr("detailed_error_messages_enabled") = false;
115106
#endif
116107

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

tests/test_class.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,17 @@
66
import pytest
77

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

12+
UINT32MAX = 2**32 - 1
13+
14+
15+
def refcount_immortal(ob: object) -> int:
16+
if _is_immortal := getattr(sys, "_is_immortal", None):
17+
return UINT32MAX if _is_immortal(ob) else sys.getrefcount(ob)
18+
return sys.getrefcount(ob)
19+
1220

1321
def test_obj_class_name():
1422
expected_name = "UserType" if env.PYPY else "pybind11_tests.UserType"
@@ -382,24 +390,21 @@ def test_brace_initialization():
382390
@pytest.mark.xfail("env.PYPY or env.GRAALPY")
383391
def test_class_refcount():
384392
"""Instances must correctly increase/decrease the reference count of their types (#1029)"""
385-
from sys import getrefcount
386393

387394
class PyDog(m.Dog):
388395
pass
389396

390397
for cls in m.Dog, PyDog:
391-
refcount_1 = getrefcount(cls)
398+
refcount_1 = refcount_immortal(cls)
392399
molly = [cls("Molly") for _ in range(10)]
393-
refcount_2 = getrefcount(cls)
400+
refcount_2 = refcount_immortal(cls)
394401

395402
del molly
396403
pytest.gc_collect()
397-
refcount_3 = getrefcount(cls)
404+
refcount_3 = refcount_immortal(cls)
398405

399406
assert refcount_1 == refcount_3
400-
assert (refcount_2 > refcount_1) or (
401-
is_immortal(refcount_2) and is_immortal(refcount_1)
402-
)
407+
assert (refcount_2 > refcount_1) or (refcount_2 == refcount_1 == UINT32MAX)
403408

404409

405410
def test_reentrant_implicit_conversion_failure(msg):

0 commit comments

Comments
 (0)