Skip to content

Commit 948acd6

Browse files
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 <[email protected]>
1 parent e3dedea commit 948acd6

File tree

3 files changed

+13
-0
lines changed

3 files changed

+13
-0
lines changed

Lib/test/test_bytes.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1599,6 +1599,13 @@ def test_extend(self):
15991599
a = bytearray(b'')
16001600
a.extend([Indexable(ord('a'))])
16011601
self.assertEqual(a, b'a')
1602+
a = bytearray(b'abc')
1603+
self.assertRaisesRegex(TypeError, # Override for string.
1604+
"expected iterable of integers; got: 'str'",
1605+
a.extend, 'def')
1606+
self.assertRaisesRegex(TypeError, # But not for others.
1607+
"can't extend bytearray with float",
1608+
a.extend, 1.0)
16021609

16031610
def test_remove(self):
16041611
b = bytearray(b'hello')
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Make error message more meaningful for when :meth:`bytearray.extend` is
2+
called with a :class:`str` object.

Objects/bytearrayobject.c

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1729,6 +1729,10 @@ bytearray_extend(PyByteArrayObject *self, PyObject *iterable_of_ints)
17291729

17301730
while ((item = PyIter_Next(it)) != NULL) {
17311731
if (! _getbytevalue(item, &value)) {
1732+
if (PyErr_ExceptionMatches(PyExc_TypeError) && PyUnicode_Check(iterable_of_ints)) {
1733+
PyErr_Format(PyExc_TypeError,
1734+
"expected iterable of integers; got: 'str'");
1735+
}
17321736
Py_DECREF(item);
17331737
Py_DECREF(it);
17341738
Py_DECREF(bytearray_obj);

0 commit comments

Comments
 (0)