[Python-checkins] gh-91020: Add `PyBytes_Type.tp_alloc` for subclass (GH-91686)

methane webhook-mailer at python.org
Wed Apr 20 01:06:41 EDT 2022


https://github.com/python/cpython/commit/4d2403fd5017324515016a8fad8545935a5c81ef
commit: 4d2403fd5017324515016a8fad8545935a5c81ef
branch: main
author: Inada Naoki <songofacandy at gmail.com>
committer: methane <songofacandy at gmail.com>
date: 2022-04-20T14:06:29+09:00
summary:

gh-91020: Add `PyBytes_Type.tp_alloc` for subclass (GH-91686)

files:
A Misc/NEWS.d/next/C API/2022-04-19-17-05-39.gh-issue-91020.BVJ8F3.rst
M 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
index 0000000000000..1572c961de34c
--- /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 d0124c050d1e1..510a836e6b152 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 */
 };



More information about the Python-checkins mailing list