diff options
| author | Serhiy Storchaka <storchaka@gmail.com> | 2024-05-28 09:01:37 (GMT) |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-05-28 09:01:37 (GMT) |
| commit | b313cc68d50de5fb5f43acffd402c5c4da6516fc (patch) | |
| tree | 3d25305bb921d8e3748db524ec9267e65ecb242f /Objects/bytesobject.c | |
| parent | bf08f0a5fe5750904aa4a239945db16d2c43f6e7 (diff) | |
| download | cpython-b313cc68d50de5fb5f43acffd402c5c4da6516fc.zip cpython-b313cc68d50de5fb5f43acffd402c5c4da6516fc.tar.gz cpython-b313cc68d50de5fb5f43acffd402c5c4da6516fc.tar.bz2 | |
gh-117557: Improve error messages when a string, bytes or bytearray of length 1 are expected (GH-117631)
Diffstat (limited to 'Objects/bytesobject.c')
| -rw-r--r-- | Objects/bytesobject.c | 29 |
1 files changed, 20 insertions, 9 deletions
diff --git a/Objects/bytesobject.c b/Objects/bytesobject.c index 0f6435d..459df6c 100644 --- a/Objects/bytesobject.c +++ b/Objects/bytesobject.c @@ -477,21 +477,32 @@ formatlong(PyObject *v, int flags, int prec, int type) static int byte_converter(PyObject *arg, char *p) { - if (PyBytes_Check(arg) && PyBytes_GET_SIZE(arg) == 1) { + if (PyBytes_Check(arg)) { + if (PyBytes_GET_SIZE(arg) != 1) { + PyErr_Format(PyExc_TypeError, + "%%c requires an integer in range(256) or " + "a single byte, not a bytes object of length %zd", + PyBytes_GET_SIZE(arg)); + return 0; + } *p = PyBytes_AS_STRING(arg)[0]; return 1; } - else if (PyByteArray_Check(arg) && PyByteArray_GET_SIZE(arg) == 1) { + else if (PyByteArray_Check(arg)) { + if (PyByteArray_GET_SIZE(arg) != 1) { + PyErr_Format(PyExc_TypeError, + "%%c requires an integer in range(256) or " + "a single byte, not a bytearray object of length %zd", + PyByteArray_GET_SIZE(arg)); + return 0; + } *p = PyByteArray_AS_STRING(arg)[0]; return 1; } - else { + else if (PyIndex_Check(arg)) { int overflow; long ival = PyLong_AsLongAndOverflow(arg, &overflow); if (ival == -1 && PyErr_Occurred()) { - if (PyErr_ExceptionMatches(PyExc_TypeError)) { - goto onError; - } return 0; } if (!(0 <= ival && ival <= 255)) { @@ -503,9 +514,9 @@ byte_converter(PyObject *arg, char *p) *p = (char)ival; return 1; } - onError: - PyErr_SetString(PyExc_TypeError, - "%c requires an integer in range(256) or a single byte"); + PyErr_Format(PyExc_TypeError, + "%%c requires an integer in range(256) or a single byte, not %T", + arg); return 0; } |
