On this page
decimal.localcontext
Prev: decimal.InvalidOperation | Up: decimal | Next: decimal.Overflow
Rel: decimal.Clamped, decimal.Context, decimal.ConversionSyntax, decimal.Decimal
Ref: docs.python.org — decimal.localcontext
Tags: #public #python3 #stdlib #decimal
Import
import decimal
from decimal import localcontext
Signature & Overview
decimal.localcontext(ctx=None, **kwargs)
Return a context manager that will set the default context to a copy of ctx on entry to the with-statement and restore the previous default context when exiting the with-statement. If no context is specified, a copy of the current
Usage
from decimal import Decimal, ROUND_HALF_UP, localcontext
with localcontext() as ctx:
ctx.prec = 4
ctx.rounding = ROUND_HALF_UP
assert str(Decimal("2.5").quantize(Decimal("1"))) == "3"
Gotchas
- Safest way to change precision or rounding: Automatically restores the previous context on exit.
REPL Inspect
from decimal import localcontext
help(localcontext)
Linked from
Related notes
- tuts/python3/stdlib_module/decimal/InvalidOperation Linked here; links to this page; shared tags: #decimal, #stdlib
- tuts/python3/stdlib_module/decimal/Overflow Linked here; links to this page; shared tags: #decimal, #stdlib
- tuts/python3/stdlib_module/decimal/Clamped Linked here; shared tags: #decimal, #stdlib
- tuts/python3/stdlib_module/decimal/Context Linked here; shared tags: #decimal, #stdlib
- tuts/python3/stdlib_module/decimal/ConversionSyntax Linked here; shared tags: #decimal, #stdlib
- tuts/python3/stdlib_module/decimal/Decimal Linked here; shared tags: #decimal, #stdlib
- tuts/python3/stdlib_module/decimal links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/decimal/DecimalException shared tags: #decimal, #stdlib
- tuts/python3/stdlib_module/decimal/DecimalTuple shared tags: #decimal, #stdlib
- tuts/python3/stdlib_module/decimal/DivisionByZero shared tags: #decimal, #stdlib