Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Lib/_pydecimal.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 = []
Expand Down
14 changes: 14 additions & 0 deletions Lib/test/test_decimal.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Enforce format specification width and precision limits in ``_pydecimal``
to match ``_decimal`` and avoid excessive resource consumption on huge widths.
Loading