gh-117557: Improve error messages when a string, bytes or bytearray of length 1 are expected (GH-117631)

This commit is contained in:
Serhiy Storchaka 2024-05-28 12:01:37 +03:00 committed by GitHub
parent bf08f0a5fe
commit b313cc68d5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
18 changed files with 811 additions and 161 deletions

View file

@ -14057,14 +14057,21 @@ formatchar(PyObject *v)
if (PyUnicode_GET_LENGTH(v) == 1) {
return PyUnicode_READ_CHAR(v, 0);
}
goto onError;
PyErr_Format(PyExc_TypeError,
"%%c requires an int or a unicode character, "
"not a string of length %zd",
PyUnicode_GET_LENGTH(v));
return (Py_UCS4) -1;
}
else {
int overflow;
long x = PyLong_AsLongAndOverflow(v, &overflow);
if (x == -1 && PyErr_Occurred()) {
if (PyErr_ExceptionMatches(PyExc_TypeError)) {
goto onError;
PyErr_Format(PyExc_TypeError,
"%%c requires an int or a unicode character, not %T",
v);
return (Py_UCS4) -1;
}
return (Py_UCS4) -1;
}
@ -14078,11 +14085,6 @@ formatchar(PyObject *v)
return (Py_UCS4) x;
}
onError:
PyErr_SetString(PyExc_TypeError,
"%c requires int or char");
return (Py_UCS4) -1;
}
/* Parse options of an argument: flags, width, precision.