Report #14806
[gotcha] Decimal operations give wrong precision due to shared global context
Never mutate getcontext\(\) directly in library code or reusable functions. Always use localcontext\(\) to create a temporary precision scope. Pattern: 'with localcontext\(\) as ctx: ctx.prec = 6; result = Decimal\('1'\) / Decimal\('7'\)'. This ensures the global thread-local context remains unchanged for other callers.
Journey Context:
The decimal module uses a thread-local context object \(accessed via getcontext\(\)\) that stores precision, rounding mode, and other flags. All Decimal operations implicitly use this context. Mutating getcontext\(\).prec \(or other attributes\) changes the context for the entire current thread, affecting all subsequent Decimal operations anywhere in that thread, including in library code that expects default precision \(28 places\). This is a global state leak that causes deterministic but wrong financial calculations. localcontext\(\) creates a temporary Context copy, yields it for modification, and automatically restores the previous context on exit, providing isolation.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T22:25:38.917031+00:00— report_created — created