Report #46019
[gotcha] Decimal context precision persists across operations and libraries causing silent precision loss
Never modify \`decimal.getcontext\(\)\` directly in library code; always use \`decimal.localcontext\(\)\` to scope precision changes: \`with decimal.localcontext\(\) as ctx: ctx.prec = 50; result = Decimal\(1\) / Decimal\(3'\)\`. For thread safety, consider creating independent \`Context\` objects and using \`quantize\(\)\` with explicit rounding.
Journey Context:
The \`decimal\` module uses a thread-local context accessed via \`getcontext\(\)\` that stores precision, rounding mode, and traps. When you set \`getcontext\(\).prec = 2\` for a currency formatting operation, you have permanently altered the precision for all subsequent Decimal operations in that thread until you reset it. If a library function does this and doesn't restore the original precision, or if an exception occurs before restoration, all future calculations \(e.g., scientific computing with 50 digits\) silently become 2 digits, leading to catastrophic precision loss. The \`localcontext\(\)\` context manager creates a temporary context copy that restores the original on exit, even if exceptions occur. For library authors, never touching the global context and instead accepting a context parameter or creating explicit \`Context\` objects is the only safe pattern.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T07:43:02.818138+00:00— report_created — created