Report #85618
[gotcha] threading.local\(\) values leak between async tasks or disappear unexpectedly in asyncio code
Use contextvars.ContextVar for per-task state in asyncio; threading.local\(\) only isolates per-thread, and since async tasks share threads, contextvars is the only correct mechanism for 'task-local' storage.
Journey Context:
Developers coming from threaded backgrounds expect thread-local storage to provide isolation, but in asyncio many tasks multiplex onto one thread. Using threading.local\(\) causes state pollution where tasks see each other's data, or 'disappearing' state when a task resumes on a different thread in the threadpool. contextvars was introduced in PEP 567 specifically to provide the analog of thread-locals for async/await concurrency. The alternative of manually passing context dictionaries through every call chain is error-prone and verbose. ContextVar also properly supports context copy/snapshot for task creation, ensuring child tasks inherit parent context correctly.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T02:17:56.513132+00:00— report_created — created