Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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)) {
terryjreedy marked this conversation as resolved.
Show resolved Hide resolved
PyErr_Format(PyExc_TypeError,
terryjreedy marked this conversation as resolved.
Show resolved Hide resolved
"expected iterable of integers; got: 'str'");
}
Py_DECREF(item);
Py_DECREF(it);
Py_DECREF(bytearray_obj);
Expand Down