diff --git a/Lib/test/test_format.py b/Lib/test/test_format.py index 120c719b5eb79e..bc6eac99310a9c 100644 --- a/Lib/test/test_format.py +++ b/Lib/test/test_format.py @@ -287,6 +287,8 @@ def test_common_format(self): "%i format: a real number is required, not str") test_exc_common('%i', b'1', TypeError, "%i format: a real number is required, not bytes") + test_exc_common('%*r', (-maxsize - 1, 1), OverflowError, + "width too big") def test_str_format(self): testformat("%r", "\u0378", "'\\u0378'") # non printable diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-10-19-20-38-17.gh-issue-159739.78e530.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-19-20-38-17.gh-issue-159739.78e530.rst new file mode 100644 index 00000000000000..999efdac87f974 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-19-20-38-17.gh-issue-159739.78e530.rst @@ -0,0 +1,2 @@ +Raise :exc:`OverflowError` when the absolute value of a dynamic printf-style +formatting width is too large. diff --git a/Objects/bytesobject.c b/Objects/bytesobject.c index 63730630e68497..307a015a119b9f 100644 --- a/Objects/bytesobject.c +++ b/Objects/bytesobject.c @@ -752,6 +752,10 @@ _PyBytes_FormatEx(const char *format, Py_ssize_t format_len, if (width == -1 && PyErr_Occurred()) goto error; if (width < 0) { + if (width == PY_SSIZE_T_MIN) { + PyErr_SetString(PyExc_OverflowError, "width too big"); + goto error; + } flags |= F_LJUST; width = -width; } diff --git a/Objects/unicodeobject.c b/Objects/unicodeobject.c index 8023bed17d3ea9..d62ea36ed70d68 100644 --- a/Objects/unicodeobject.c +++ b/Objects/unicodeobject.c @@ -15150,6 +15150,10 @@ unicode_format_arg_parse(struct unicode_formatter_t *ctx, if (arg->width == -1 && PyErr_Occurred()) return -1; if (arg->width < 0) { + if (arg->width == PY_SSIZE_T_MIN) { + PyErr_SetString(PyExc_OverflowError, "width too big"); + return -1; + } arg->flags |= F_LJUST; arg->width = -arg->width; }