Skip to content

Commit

Permalink
pythongh-115323: Add meaningful error message for using bytearray.ext…
Browse files Browse the repository at this point in the history
…end with str (pythonGH-115332)

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

(cherry picked from commit 948acd6)

Co-authored-by: Jay Ting <65202977+jayasting98@users.noreply.github.com>
Co-authored-by: Terry Jan Reedy <tjreedy@udel.edu>
  • Loading branch information
2 people authored and miss-islington committed Feb 24, 2024
1 parent 9daf55e commit a48ec4b
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 0 deletions.
7 changes: 7 additions & 0 deletions Lib/test/test_bytes.py
Expand Up @@ -1571,6 +1571,13 @@ def test_extend(self):
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')
Expand Down
@@ -0,0 +1,2 @@
Make error message more meaningful for when :meth:`bytearray.extend` is
called with a :class:`str` object.
4 changes: 4 additions & 0 deletions Objects/bytearrayobject.c
Expand Up @@ -1730,6 +1730,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);
Expand Down

0 comments on commit a48ec4b

Please sign in to comment.