Skip to content

Pure-Python decimal returns an out-of-range integer quotient with the Overflow trap enabled #162709

Backlog

Description

@limadog9

Bug report

The pure-Python decimal implementation can return a finite result outside the active context’s exponent range without raising Overflow or setting any flags. This affects //, divmod(), and the corresponding Context methods.

import _pydecimal as decimal

ctx = decimal.Context(prec=3, Emin=-1, Emax=1)
ctx.traps[decimal.Overflow] = True
a = ctx.create_decimal("75")
b = ctx.create_decimal("0.25")

print(ctx.divide_int(a, b))
print(ctx.divmod(a, b))
print([signal.__name__ for signal, active in ctx.flags.items() if active])

Actual output:

300
(Decimal('300'), Decimal('0.00'))
[]

Expected: both operations raise decimal.Overflow. Both inputs fit the context. The exact quotient 300 fits the three-digit precision, but its adjusted exponent is 2 and Emax is 1.

Changing only the import to import _decimal as decimal makes the first operation raise Overflow. With the trap disabled, the C implementation returns Infinity for the quotient and sets Overflow, Inexact, and Rounded. The Python implementation still returns 300 with no flags. I also reproduced this through the public decimal module on a main build using the Python fallback.

Decimal._divide() checks whether the quotient fits the precision and constructs it with _dec_from_triple. __floordiv__ returns that quotient directly. __divmod__ applies _fix(context) only to the remainder. One distinction worth preserving in a fix: ctx.remainder(a, b) correctly returns 0.00 in both implementations.

The C-versus-Python differential tester skips contexts where prec > context.Emax, which includes this example. Related work on this helper and its tests: #140044 and #160482. The behavior also reproduces on Python 3.11, so it predates those changes.

CPython versions tested on:

3.11, 3.12, 3.13, 3.14, 3.15, 3.16, CPython main branch

Operating systems tested on:

Linux

Linked PRs

Activity

  1. added
    type-bug
    on Nov 27, 2026
  2. added
    stdlib
    on Nov 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibtype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions