diff --git a/Lib/_pydecimal.py b/Lib/_pydecimal.py index 4b7bfd07887bd3..d82f41564f151e 100644 --- a/Lib/_pydecimal.py +++ b/Lib/_pydecimal.py @@ -1503,8 +1503,9 @@ def __divmod__(self, other, context=None): context._raise_error(InvalidOperation, 'x % 0')) quotient, remainder = self._divide(other, context) - remainder = remainder._fix(context) - return quotient, remainder + if not other._isinfinity(): + quotient = quotient._fix(context) + return quotient, remainder._fix(context) def __rdivmod__(self, other, context=None): """Swaps self/other and returns __divmod__.""" @@ -1650,7 +1651,10 @@ def __floordiv__(self, other, context=None): else: return context._raise_error(DivisionUndefined, '0 // 0') - return self._divide(other, context)[0] + quotient = self._divide(other, context)[0] + if not other._isinfinity(): + quotient = quotient._fix(context) + return quotient def __rfloordiv__(self, other, context=None): """Swaps self/other and returns __floordiv__.""" diff --git a/Lib/test/test_decimal.py b/Lib/test/test_decimal.py index ef7aa5358b5cc6..a584cebb1bb5e6 100644 --- a/Lib/test/test_decimal.py +++ b/Lib/test/test_decimal.py @@ -3293,6 +3293,31 @@ def test_divmod(self): self.assertRaises(TypeError, c.divmod, '1', 2) self.assertRaises(TypeError, c.divmod, 1, '2') + def test_divide_int_overflow(self): + Decimal = self.decimal.Decimal + Context = self.decimal.Context + Overflow = self.decimal.Overflow + Inexact = self.decimal.Inexact + Rounded = self.decimal.Rounded + + # The quotient 300 fits in prec digits but not in Emax. The + # operators read the active context, so make it the one under test. + with self.decimal.localcontext(Context(prec=3, Emin=-1, Emax=1)) as c: + a, b = Decimal(75), Decimal('0.25') + for op in (c.divide_int, lambda x, y: c.divmod(x, y)[0], + operator.floordiv, lambda x, y: divmod(x, y)[0]): + c.traps[Overflow] = True + self.assertRaises(Overflow, op, a, b) + + c.traps[Overflow] = False + c.clear_flags() + self.assertEqual(op(a, b), Decimal('Infinity')) + for flag in (Overflow, Inexact, Rounded): + self.assertTrue(c.flags[flag]) + c.clear_flags() + self.assertEqual(c.remainder(a, b), Decimal('0.00')) + self.assertFalse(any(c.flags.values())) + def test_exp(self): Decimal = self.decimal.Decimal Context = self.decimal.Context diff --git a/Misc/NEWS.d/next/Library/2026-11-27-04-33-20.gh-issue-162709.LlWRBf.rst b/Misc/NEWS.d/next/Library/2026-11-27-04-33-20.gh-issue-162709.LlWRBf.rst new file mode 100644 index 00000000000000..f1028e39ff51a7 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-27-04-33-20.gh-issue-162709.LlWRBf.rst @@ -0,0 +1,4 @@ +Fix the pure-Python :mod:`decimal` implementation returning an out-of-range +quotient from ``//``, :func:`divmod`, :meth:`Context.divide_int +` and :meth:`Context.divmod ` +instead of signaling :exc:`~decimal.Overflow`.