diff --git a/Lib/test/test_bytes.py b/Lib/test/test_bytes.py index 0177749e212..7b66a5e2789 100644 --- a/Lib/test/test_bytes.py +++ b/Lib/test/test_bytes.py @@ -100,6 +100,14 @@ class BaseBytesTest: self.assertRaises(TypeError, self.type2test, [0.0]) self.assertRaises(TypeError, self.type2test, [None]) self.assertRaises(TypeError, self.type2test, [C()]) + self.assertRaises(TypeError, self.type2test, 0, 'ascii') + self.assertRaises(TypeError, self.type2test, b'', 'ascii') + self.assertRaises(TypeError, self.type2test, 0, errors='ignore') + self.assertRaises(TypeError, self.type2test, b'', errors='ignore') + self.assertRaises(TypeError, self.type2test, '') + self.assertRaises(TypeError, self.type2test, '', errors='ignore') + self.assertRaises(TypeError, self.type2test, '', b'ascii') + self.assertRaises(TypeError, self.type2test, '', 'ascii', b'ignore') def test_constructor_value_errors(self): self.assertRaises(ValueError, self.type2test, [-1]) diff --git a/Misc/NEWS b/Misc/NEWS index d820bb66ed6..f48a794c3bd 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -11,6 +11,9 @@ Release date: TBA Core and Builtins ----------------- +- Issue #20335: bytes constructor now raises TypeError when encoding or errors + is specified with non-string argument. Based on patch by Renaud Blanch. + - Issue #22335: Fix crash when trying to enlarge a bytearray to 0x7fffffff bytes on a 32-bit platform. diff --git a/Objects/bytesobject.c b/Objects/bytesobject.c index 4a8561cf2f3..a3ccbcfd613 100644 --- a/Objects/bytesobject.c +++ b/Objects/bytesobject.c @@ -2503,6 +2503,13 @@ bytes_new(PyTypeObject *type, PyObject *args, PyObject *kwds) return new; } + /* If it's not unicode, there can't be encoding or errors */ + if (encoding != NULL || errors != NULL) { + PyErr_SetString(PyExc_TypeError, + "encoding or errors without a string argument"); + return NULL; + } + /* We'd like to call PyObject_Bytes here, but we need to check for an integer argument before deferring to PyBytes_FromObject, something PyObject_Bytes doesn't do. */ @@ -2544,13 +2551,6 @@ bytes_new(PyTypeObject *type, PyObject *args, PyObject *kwds) return new; } - /* If it's not unicode, there can't be encoding or errors */ - if (encoding != NULL || errors != NULL) { - PyErr_SetString(PyExc_TypeError, - "encoding or errors without a string argument"); - return NULL; - } - return PyBytes_FromObject(x); }