all Python 3Numbers & mathfunction
decimal.localcontext()
decimal
A context manager: inside the with block a copy of the decimal context with different settings is active, and the old one is restored on exit.
Syntax
with decimal.localcontext(ctx=None, **kwargs) as ctx: ...
The classic trap is getcontext().prec = 50: it changes precision for the whole thread until the program ends, including other people's functions and tests. localcontext() limits the change to the with block and restores the old context even on an exception. Numbers computed inside keep their extra digits outside, so round them with unary plus (+x) after the block.
Examples
# Python 3.11+
from decimal import Decimal, localcontext
with localcontext(prec=5):
x = Decimal(1) / 3
print(x) # → 0.33333
print(Decimal(1) / 3) # → 0.3333333333333333333333333333
from decimal import Decimal, getcontext
getcontext().prec = 3
print(Decimal(2) / 3) # → 0.667 — и так теперь везде
See also
Open in the full glossarydocs.python.orgReport an inaccuracy