]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-115323: Add meaningful error message for using bytearray.extend with str (#115332)
authorJay Ting <65202977+jayasting98@users.noreply.github.com>
Sat, 24 Feb 2024 23:34:45 +0000 (07:34 +0800)
committerGitHub <noreply@github.com>
Sat, 24 Feb 2024 23:34:45 +0000 (18:34 -0500)
Perform str check after TypeError is raised
---------

Co-authored-by: Terry Jan Reedy <tjreedy@udel.edu>
Lib/test/test_bytes.py
Misc/NEWS.d/next/Core and Builtins/2024-02-12-23-29-17.gh-issue-115323.3t6687.rst [new file with mode: 0644]
Objects/bytearrayobject.c

index a3804a945f2e3a4fe7d80c69bb3a4e2e3880d6dc..71bb1e75c6affd71041a0c4d8fd6c781469dbe5d 100644 (file)
@@ -1599,6 +1599,13 @@ class ByteArrayTest(BaseBytesTest, unittest.TestCase):
         a = bytearray(b'')
         a.extend([Indexable(ord('a'))])
         self.assertEqual(a, b'a')
+        a = bytearray(b'abc')
+        self.assertRaisesRegex(TypeError,  # Override for string.
+                               "expected iterable of integers; got: 'str'",
+                               a.extend, 'def')
+        self.assertRaisesRegex(TypeError,  # But not for others.
+                               "can't extend bytearray with float",
+                               a.extend, 1.0)
 
     def test_remove(self):
         b = bytearray(b'hello')
diff --git a/Misc/NEWS.d/next/Core and Builtins/2024-02-12-23-29-17.gh-issue-115323.3t6687.rst b/Misc/NEWS.d/next/Core and Builtins/2024-02-12-23-29-17.gh-issue-115323.3t6687.rst
new file mode 100644 (file)
index 0000000..1718556
--- /dev/null
@@ -0,0 +1,2 @@
+Make error message more meaningful for when :meth:`bytearray.extend` is
+called with a :class:`str` object.
index acc59b926448ca43359981289720391c6b902f02..5e3b3affbc76c53cd74f936f25e002e41e946da5 100644 (file)
@@ -1729,6 +1729,10 @@ bytearray_extend(PyByteArrayObject *self, PyObject *iterable_of_ints)
 
     while ((item = PyIter_Next(it)) != NULL) {
         if (! _getbytevalue(item, &value)) {
+            if (PyErr_ExceptionMatches(PyExc_TypeError) && PyUnicode_Check(iterable_of_ints)) {
+                PyErr_Format(PyExc_TypeError,
+                             "expected iterable of integers; got: 'str'");
+            }
             Py_DECREF(item);
             Py_DECREF(it);
             Py_DECREF(bytearray_obj);