From 9ea197627d225f0109589e9fb392b4c6648564fe Mon Sep 17 00:00:00 2001 From: Sam Gross Date: Sun, 5 Oct 2025 12:58:13 -0400 Subject: [PATCH] Use new 3.14 C APIs when available (#5854) * Use new 3.14 C APIs when available Use the new "unstable" C APIs for the functions added in #5494. * style: pre-commit fixes --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- include/pybind11/detail/class.h | 6 ++++-- include/pybind11/detail/type_caster_base.h | 6 +++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/include/pybind11/detail/class.h b/include/pybind11/detail/class.h index 64e371db4..74b70489c 100644 --- a/include/pybind11/detail/class.h +++ b/include/pybind11/detail/class.h @@ -314,8 +314,9 @@ inline void traverse_offset_bases(void *valueptr, #ifdef Py_GIL_DISABLED inline void enable_try_inc_ref(PyObject *obj) { - // TODO: Replace with PyUnstable_Object_EnableTryIncRef when available. - // See https://github.com/python/cpython/issues/128844 +# if PY_VERSION_HEX >= 0x030E00A4 + PyUnstable_EnableTryIncRef(obj); +# else if (_Py_IsImmortal(obj)) { return; } @@ -330,6 +331,7 @@ inline void enable_try_inc_ref(PyObject *obj) { return; } } +# endif } #endif diff --git a/include/pybind11/detail/type_caster_base.h b/include/pybind11/detail/type_caster_base.h index 79346cf6a..3564bb242 100644 --- a/include/pybind11/detail/type_caster_base.h +++ b/include/pybind11/detail/type_caster_base.h @@ -253,9 +253,9 @@ PYBIND11_NOINLINE handle get_type_handle(const std::type_info &tp, bool throw_if inline bool try_incref(PyObject *obj) { // Tries to increment the reference count of an object if it's not zero. - // TODO: Use PyUnstable_TryIncref when available. - // See https://github.com/python/cpython/issues/128844 -#ifdef Py_GIL_DISABLED +#if defined(Py_GIL_DISABLED) && PY_VERSION_HEX >= 0x030E00A4 + return PyUnstable_TryIncRef(obj); +#elif defined(Py_GIL_DISABLED) // See // https://github.com/python/cpython/blob/d05140f9f77d7dfc753dd1e5ac3a5962aaa03eff/Include/internal/pycore_object.h#L761 uint32_t local = _Py_atomic_load_uint32_relaxed(&obj->ob_ref_local);