Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
gh-115323: Add meaningful error message for using bytearray.extend wi…
…th str (GH-115332)

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

(cherry picked from commit 948acd6)

Co-authored-by: Jay Ting <[email protected]>
Co-authored-by: Terry Jan Reedy <[email protected]>
  • Loading branch information
2 people authored and miss-islington committed Feb 24, 2024
commit 9263aed62ff00947cfd867645a582810d77fb14e
7 changes: 7 additions & 0 deletions Lib/test/test_bytes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1599,6 +1599,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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down