diff --git a/docs/api.rst b/docs/api.rst index ad9c4fd..2f0e7f6 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -67,6 +67,15 @@ Python 3.13 See `PyWeakref_GetRef() documentation `__. +.. c:function:: int Py_IsFinalizing() + + Return non-zero if the Python interpreter is shutting down, return 0 + otherwise. + + Availability: Python 3.3 and newer, PyPy 7.3 and newer. + + See `Py_IsFinalizing() documentation `__. + Python 3.12 ----------- diff --git a/docs/changelog.rst b/docs/changelog.rst index d017844..fcbf1a2 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,6 +1,7 @@ Changelog ========= +* 2023-08-16: Add ``Py_IsFinalizing()`` function. * 2023-07-21: Add ``PyDict_GetItemRef()`` function. * 2023-07-18: Add ``PyModule_Add()`` function. * 2023-07-12: Add ``PyObject_GetOptionalAttr()``, diff --git a/pythoncapi_compat.h b/pythoncapi_compat.h index 2a87a55..ff9f411 100644 --- a/pythoncapi_compat.h +++ b/pythoncapi_compat.h @@ -846,6 +846,24 @@ PyModule_Add(PyObject *mod, const char *name, PyObject *value) #endif +// gh-108014 added Py_IsFinalizing() to Python 3.13.0a1 +// bpo-1856 added _Py_Finalizing to Python 3.2.1b1. +// Py_IsFinalizing() was added to PyPy 7.3.0. +#if (0x030201B1 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x030D00A1) \ + && (!defined(PYPY_VERSION_NUM) || PYPY_VERSION_NUM >= 0x7030000) +PYCAPI_COMPAT_STATIC_INLINE(int) +Py_IsFinalizing(void) +{ +#if PY_VERSION_HEX >= 0x030700A1 + // _Py_IsFinalizing() was added to Python 3.7.0a1. + return _Py_IsFinalizing(); +#else + return (_Py_Finalizing != NULL); +#endif +} +#endif + + #ifdef __cplusplus } #endif diff --git a/tests/test_pythoncapi_compat_cext.c b/tests/test_pythoncapi_compat_cext.c index 13c0edf..0213556 100644 --- a/tests/test_pythoncapi_compat_cext.c +++ b/tests/test_pythoncapi_compat_cext.c @@ -328,6 +328,11 @@ test_interpreter(PyObject *Py_UNUSED(module), PyObject* Py_UNUSED(ignored)) PyInterpreterState *interp2 = PyThreadState_GetInterpreter(tstate); assert(interp == interp2); +#if 0x030300A1 <= PY_VERSION_HEX && (!defined(PYPY_VERSION_NUM) || PYPY_VERSION_NUM >= 0x7030000) + // test Py_IsFinalizing() + assert(Py_IsFinalizing() == 0); +#endif + Py_RETURN_NONE; }