From 837f1215617dfd3f842b1a6cfa12da38c4c9fced Mon Sep 17 00:00:00 2001 From: Victor Stinner Date: Tue, 14 Oct 2025 15:54:08 +0200 Subject: [PATCH] Add PyUnstable_Unicode_GET_CACHED_HASH() function --- docs/api.rst | 6 ++++++ docs/changelog.rst | 6 +++++- pythoncapi_compat.h | 13 +++++++++++++ tests/test_pythoncapi_compat_cext.c | 7 +++++++ 4 files changed, 31 insertions(+), 1 deletion(-) diff --git a/docs/api.rst b/docs/api.rst index de80e3d..7b64c64 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -64,6 +64,12 @@ Python 3.15 See `PyTuple_FromArray() documentation `__. +.. c:function:: Py_hash_t PyUnstable_Unicode_GET_CACHED_HASH(PyObject *op) + + See `PyUnstable_Unicode_GET_CACHED_HASH() documentation `__. + + Not available on PyPy. + Python 3.14 ----------- diff --git a/docs/changelog.rst b/docs/changelog.rst index 2d84389..007a665 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,7 +1,11 @@ Changelog ========= -* 2025-10-14: Add ``PyTuple_FromArray()`` function. +* 2025-10-14: Add functions: + + * ``PyTuple_FromArray()`` + * ``PyUnstable_Unicode_GET_CACHED_HASH()`` + * 2025-09-18: Add PEP 782 functions: * ``PyBytesWriter_Create()`` diff --git a/pythoncapi_compat.h b/pythoncapi_compat.h index 55b2dbd..85c6cd5 100644 --- a/pythoncapi_compat.h +++ b/pythoncapi_compat.h @@ -2570,6 +2570,19 @@ PyTuple_FromArray(PyObject *const *array, Py_ssize_t size) #endif +#if PY_VERSION_HEX < 0x030F00A1 && !defined(PYPY_VERSION) +static inline Py_hash_t +PyUnstable_Unicode_GET_CACHED_HASH(PyObject *op) +{ +#if PY_VERSION_HEX >= 0x03000000 + return ((PyASCIIObject*)op)->hash; +#else + return ((PyUnicodeObject*)op)->hash; +#endif +} +#endif + + #ifdef __cplusplus } #endif diff --git a/tests/test_pythoncapi_compat_cext.c b/tests/test_pythoncapi_compat_cext.c index 25c7499..dd8c54b 100644 --- a/tests/test_pythoncapi_compat_cext.c +++ b/tests/test_pythoncapi_compat_cext.c @@ -1611,6 +1611,13 @@ test_unicode(PyObject *Py_UNUSED(module), PyObject *Py_UNUSED(args)) assert(PyErr_ExceptionMatches(PyExc_TypeError)); PyErr_Clear(); +#ifndef PYPY_VERSION + // Test PyUnstable_Unicode_GET_CACHED_HASH() + Py_hash_t hash = PyObject_Hash(abc); + assert(hash != -1); + assert(PyUnstable_Unicode_GET_CACHED_HASH(abc) == hash); +#endif + Py_DECREF(abc); Py_DECREF(abc0def); Py_RETURN_NONE;