Report #67643
[gotcha] Decimal precision lost or inconsistent in multi-threaded Python applications
Never rely on global precision settings via getcontext\(\).prec in multi-threaded code. Always use the localcontext\(\) context manager within the specific function or block performing calculations, explicitly setting the precision there. Alternatively, pass a Context object explicitly to Decimal operations using the context parameter where available.
Journey Context:
The decimal module maintains a thread-local context via getcontext\(\), which stores precision, rounding mode, and traps. Modifications to getcontext\(\) in one thread do not affect other threads, which use a fresh default context. This leads to bugs where the main thread configures high precision \(e.g., 50 digits\), but worker threads use the default \(28 digits\), silently truncating results. Furthermore, arithmetic operations capture the current context at execution time, not at Decimal instantiation, making behavior dependent on the thread's state during the operation, not creation. Alternatives: \(1\) Setting context at module level in each thread - fragile, relies on thread-local inheritance; \(2\) Using the quantize\(\) method which is independent of context precision - good for final formatting but not intermediate calculations; \(3\) Using localcontext\(\) to explicitly scope precision - ensures the correct context is used regardless of thread state. The correct pattern is explicit context management around calculation blocks.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T20:01:18.189678+00:00— report_created — created