gh-115323: Add meaningful error message for using bytearray.extend with str (#115332)

Perform str check after TypeError is raised
---------

Co-authored-by: Terry Jan Reedy <tjreedy@udel.edu>
This commit is contained in:
Jay Ting 2024-02-25 07:34:45 +08:00 committed by GitHub
parent e3dedeae7a
commit 948acd6ed8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 13 additions and 0 deletions

View File

@ -1599,6 +1599,13 @@ class ByteArrayTest(BaseBytesTest, unittest.TestCase):
a = bytearray(b'') a = bytearray(b'')
a.extend([Indexable(ord('a'))]) a.extend([Indexable(ord('a'))])
self.assertEqual(a, b'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): def test_remove(self):
b = bytearray(b'hello') b = bytearray(b'hello')

View File

@ -0,0 +1,2 @@
Make error message more meaningful for when :meth:`bytearray.extend` is
called with a :class:`str` object.

View File

@ -1729,6 +1729,10 @@ bytearray_extend(PyByteArrayObject *self, PyObject *iterable_of_ints)
while ((item = PyIter_Next(it)) != NULL) { while ((item = PyIter_Next(it)) != NULL) {
if (! _getbytevalue(item, &value)) { 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(item);
Py_DECREF(it); Py_DECREF(it);
Py_DECREF(bytearray_obj); Py_DECREF(bytearray_obj);