]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-91020: Add `PyBytes_Type.tp_alloc` for subclass (GH-91686)
authorInada Naoki <songofacandy@gmail.com>
Wed, 20 Apr 2022 05:06:29 +0000 (14:06 +0900)
committerGitHub <noreply@github.com>
Wed, 20 Apr 2022 05:06:29 +0000 (14:06 +0900)
Misc/NEWS.d/next/C API/2022-04-19-17-05-39.gh-issue-91020.BVJ8F3.rst [new file with mode: 0644]
Objects/bytesobject.c

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 (file)
index 0000000..1572c96
--- /dev/null
@@ -0,0 +1,2 @@
+Add ``PyBytes_Type.tp_alloc`` to initialize ``PyBytesObject.ob_shash`` for
+bytes subclasses.
index d0124c050d1e173580c29292f11f6b35515c33ee..510a836e6b15206f90e73d25b60e15b6717ea9eb 100644 (file)
@@ -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 */
 };