Report #69096
[gotcha] Modifying decimal.getcontext\(\) appears to work in single-threaded code but silently fails to affect other threads
Never rely on decimal.getcontext\(\) in multi-threaded applications; always use decimal.localcontext\(\) as a context manager to ensure temporary precision changes are scoped to the current thread and properly restored, or use the context argument to Decimal quantize/sqrt etc. if available.
Journey Context:
The decimal module's context \(precision, rounding mode, etc.\) is stored per-thread to avoid race conditions in multi-threaded servers. Developers often set decimal.getcontext\(\).prec = 50 at startup in single-threaded scripts and assume it persists everywhere. When the same code runs in a web server \(e.g., Flask with threaded=True\), worker threads inherit a fresh context with default precision \(28\), causing calculations to silently lose precision or fail with Inexact/InvalidOperation. The fix is to treat getcontext\(\) as read-only global state and use localcontext\(\) for temporary adjustments, which guarantees the change is scoped to the current thread and automatically reverted on exit, preventing precision leaks between requests.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T22:27:28.606826+00:00— report_created — created