You misinterpret the documentation; the operation returns the rounded result only when you don't trap, instead the Inexact
flag is set on the context.
But when you trap the exception instead, it is raised and no rounded result is returned.
From the tutorial portion of the documentation:
Contexts also have signal flags for monitoring exceptional conditions encountered during computations. The flags remain set until explicitly cleared, so it is best to clear the flags before each set of monitored computations by using the
clear_flags()
method.
>>> from decimal import localcontext
>>> with localcontext() as ctx:
... (Decimal("1.23")/2).quantize(Decimal("0.1"))
... print(ctx.flags)
...
Decimal('0.6')
{<class 'decimal.Subnormal'>: 0, <class 'decimal.Underflow'>: 0, <class 'decimal.DivisionByZero'>: 0, <class 'decimal.Inexact'>: 1, <class 'decimal.Rounded'>: 1, <class 'decimal.InvalidOperation'>: 0, <class 'decimal.Overflow'>: 0, <class 'decimal.Clamped'>: 0}
Here the decimal.Inexact
and decimal.Rounded
flags are set, telling you that the Decimal('0.6')
return value is inexact.
Use trapping only when the specific signal should be an error; e.g. when rounding would be a problem for your application.