From a48ec4bf1990dd79c0fe116f516804af5838ed4e Mon Sep 17 00:00:00 2001 From: Jay Ting <65202977+jayasting98@users.noreply.github.com> Date: Sun, 25 Feb 2024 07:34:45 +0800 Subject: [PATCH] gh-115323: Add meaningful error message for using bytearray.extend with str (GH-115332) Perform str check after TypeError is raised --------- (cherry picked from commit 948acd6ed856251dc5889cc34cf7a58210c4f9a9) Co-authored-by: Jay Ting <65202977+jayasting98@users.noreply.github.com> Co-authored-by: Terry Jan Reedy --- Lib/test/test_bytes.py | 7 +++++++ .../2024-02-12-23-29-17.gh-issue-115323.3t6687.rst | 2 ++ Objects/bytearrayobject.c | 4 ++++ 3 files changed, 13 insertions(+) create mode 100644 Misc/NEWS.d/next/Core and Builtins/2024-02-12-23-29-17.gh-issue-115323.3t6687.rst diff --git a/Lib/test/test_bytes.py b/Lib/test/test_bytes.py index f5605ca3c2c53b..093e5c326e2840 100644 --- a/Lib/test/test_bytes.py +++ b/Lib/test/test_bytes.py @@ -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') diff --git a/Misc/NEWS.d/next/Core and Builtins/2024-02-12-23-29-17.gh-issue-115323.3t6687.rst b/Misc/NEWS.d/next/Core and Builtins/2024-02-12-23-29-17.gh-issue-115323.3t6687.rst new file mode 100644 index 00000000000000..171855608fbc6a --- /dev/null +++ b/Misc/NEWS.d/next/Core and Builtins/2024-02-12-23-29-17.gh-issue-115323.3t6687.rst @@ -0,0 +1,2 @@ +Make error message more meaningful for when :meth:`bytearray.extend` is +called with a :class:`str` object. diff --git a/Objects/bytearrayobject.c b/Objects/bytearrayobject.c index 1c502030842120..813535dbb7cf90 100644 --- a/Objects/bytearrayobject.c +++ b/Objects/bytearrayobject.c @@ -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);