From 4d2403fd5017324515016a8fad8545935a5c81ef Mon Sep 17 00:00:00 2001 From: Inada Naoki Date: Wed, 20 Apr 2022 14:06:29 +0900 Subject: [PATCH] gh-91020: Add `PyBytes_Type.tp_alloc` for subclass (GH-91686) --- ...2-04-19-17-05-39.gh-issue-91020.BVJ8F3.rst | 2 ++ Objects/bytesobject.c | 21 ++++++++++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/C API/2022-04-19-17-05-39.gh-issue-91020.BVJ8F3.rst diff --git a/Misc/NEWS.d/next/C API/2022-04-19-17-05-39.gh-issue-91020.BVJ8F3.rst b/Misc/NEWS.d/next/C API/2022-04-19-17-05-39.gh-issue-91020.BVJ8F3.rst new file mode 100644 index 00000000000..1572c961de3 --- /dev/null +++ b/Misc/NEWS.d/next/C API/2022-04-19-17-05-39.gh-issue-91020.BVJ8F3.rst @@ -0,0 +1,2 @@ +Add ``PyBytes_Type.tp_alloc`` to initialize ``PyBytesObject.ob_shash`` for +bytes subclasses. diff --git a/Objects/bytesobject.c b/Objects/bytesobject.c index d0124c050d1..510a836e6b1 100644 --- a/Objects/bytesobject.c +++ b/Objects/bytesobject.c @@ -2861,6 +2861,25 @@ PyBytes_FromObject(PyObject *x) return NULL; } +/* This allocator is needed for subclasses don't want to use __new__. + * See https://github.com/python/cpython/issues/91020#issuecomment-1096793239 + * + * This allocator will be removed when ob_shash is removed. + */ +static PyObject * +bytes_alloc(PyTypeObject *self, Py_ssize_t nitems) +{ + PyBytesObject *obj = (PyBytesObject*)PyType_GenericAlloc(self, nitems); + if (obj == NULL) { + return NULL; + } +_Py_COMP_DIAG_PUSH +_Py_COMP_DIAG_IGNORE_DEPR_DECLS + obj->ob_shash = -1; +_Py_COMP_DIAG_POP + return (PyObject*)obj; +} + static PyObject * bytes_subtype_new(PyTypeObject *type, PyObject *tmp) { @@ -2937,7 +2956,7 @@ PyTypeObject PyBytes_Type = { 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ - 0, /* tp_alloc */ + bytes_alloc, /* tp_alloc */ bytes_new, /* tp_new */ PyObject_Del, /* tp_free */ };