diff --git a/Lib/_pydecimal.py b/Lib/_pydecimal.py index 4b7bfd07887bd3..5b9614bc0723b8 100644 --- a/Lib/_pydecimal.py +++ b/Lib/_pydecimal.py @@ -6323,8 +6323,12 @@ def _parse_format_specifier(format_spec, _localeconv=None): # minimumwidth defaults to 0; precision remains None if not given format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0') + if format_dict['minimumwidth'] > MAX_PREC: + raise ValueError("format specification exceeds internal limits of _decimal") if format_dict['precision'] is not None: format_dict['precision'] = int(format_dict['precision']) + if format_dict['precision'] > MAX_PREC: + raise ValueError("format specification exceeds internal limits of _decimal") # if format type is 'g' or 'G' then a precision of 0 makes little # sense; convert it to 1. Same if format type is unspecified. @@ -6424,6 +6428,12 @@ def _insert_thousands_sep(digits, spec, min_width=1): """ sep = spec['thousands_sep'] + if not sep: + pad = max(min_width, 1 if not digits else 0) - len(digits) + if pad > 0: + return '0' * pad + digits + return digits + grouping = spec['grouping'] groups = [] diff --git a/Lib/test/test_decimal.py b/Lib/test/test_decimal.py index ef7aa5358b5cc6..bfa6938dc5f10e 100644 --- a/Lib/test/test_decimal.py +++ b/Lib/test/test_decimal.py @@ -1326,6 +1326,20 @@ def __init__(self, a): a = A.from_float(42) self.assertEqual(self.decimal.Decimal, a.a_type) + def test_format_limits(self): + Decimal = self.decimal.Decimal + limit = self.decimal.MAX_PREC + 1 + with self.assertRaises(ValueError): + format(Decimal('1.5'), f'{limit}') + with self.assertRaises(ValueError): + format(Decimal('1.5'), f'.{limit}f') + with self.assertRaises(ValueError): + format(Decimal('1.5'), f'#0{limit}') + # Verify that large padding without thousands separator formats correctly + res = format(Decimal('1.5'), '#01000') + self.assertEqual(len(res), 1000) + self.assertTrue(res.startswith('000') and res.endswith('1.5')) + @requires_cdecimal class CFormatTest(FormatTest, unittest.TestCase): decimal = C diff --git a/Misc/NEWS.d/next/Library/2026-11-21-13-59-00.gh-issue-162375.xK9L2P.rst b/Misc/NEWS.d/next/Library/2026-11-21-13-59-00.gh-issue-162375.xK9L2P.rst new file mode 100644 index 00000000000000..04c928136f5b8e --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-21-13-59-00.gh-issue-162375.xK9L2P.rst @@ -0,0 +1,2 @@ +Enforce format specification width and precision limits in ``_pydecimal`` +to match ``_decimal`` and avoid excessive resource consumption on huge widths.