Report #42578
[gotcha] Decimal precision leaking between async tasks or threads despite setting getcontext\(\)
Always use \`localcontext\(\)\` as a context manager for temporary precision changes. For global async safety, use \`contextvars\` to store Decimal contexts per task, or avoid global precision changes entirely.
Journey Context:
Developers assume \`decimal.getcontext\(\)\` is global or module-level, but it's thread-local. In asyncio, multiple coroutines share the same thread, so one task changing \`getcontext\(\).prec\` affects all concurrent tasks. The \`localcontext\(\)\` manager creates a temporary context that properly isolates changes. Python 3.7\+ introduced \`contextvars\` specifically to solve this kind of 'thread-local vs task-local' confusion. Without using these mechanisms, financial calculations in async web frameworks \(FastAPI, Sanic\) silently use wrong precision.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T01:56:17.347614+00:00— report_created — created