diff --git a/Misc/NEWS.d/next/C_API/2025-11-15-05-35-00.gh-issue-141578.HAlryh.rst b/Misc/NEWS.d/next/C_API/2025-11-15-05-35-00.gh-issue-141578.HAlryh.rst new file mode 100644 index 00000000000000..24e426d9c61545 --- /dev/null +++ b/Misc/NEWS.d/next/C_API/2025-11-15-05-35-00.gh-issue-141578.HAlryh.rst @@ -0,0 +1,3 @@ +Improve overflow error messages in :c:func:`PyLong_AsLong` and :c:func:`PyLong_AsInt` +to indicate whether the value exceeds the maximum or minimum bounds, instead of +showing generic overflow messages. diff --git a/Objects/longobject.c b/Objects/longobject.c index 43c0db753a0fb9..8368a90903642f 100644 --- a/Objects/longobject.c +++ b/Objects/longobject.c @@ -669,10 +669,18 @@ PyLong_AsLong(PyObject *obj) int overflow; long result = PyLong_AsLongAndOverflow(obj, &overflow); if (overflow) { - /* XXX: could be cute and give a different - message for overflow == -1 */ - PyErr_SetString(PyExc_OverflowError, - "Python int too large to convert to C long"); + if (overflow > 0) { + PyErr_Format(PyExc_OverflowError, + "Python int too large to convert to C long: " + "value would be greater than %ld", + LONG_MAX); + } + else { + PyErr_Format(PyExc_OverflowError, + "Python int too large to convert to C long: " + "value would be less than %ld", + LONG_MIN); + } } return result; } @@ -686,10 +694,18 @@ PyLong_AsInt(PyObject *obj) int overflow; long result = PyLong_AsLongAndOverflow(obj, &overflow); if (overflow || result > INT_MAX || result < INT_MIN) { - /* XXX: could be cute and give a different - message for overflow == -1 */ - PyErr_SetString(PyExc_OverflowError, - "Python int too large to convert to C int"); + if (overflow > 0 || result > INT_MAX) { + PyErr_Format(PyExc_OverflowError, + "Python int too large to convert to C int: " + "value would be greater than %d", + INT_MAX); + } + else { + PyErr_Format(PyExc_OverflowError, + "Python int too large to convert to C int: " + "value would be less than %d", + INT_MIN); + } return -1; } return (int)result;