Context Variables in Async Coroutines with contextvars
`threading.local()` fails catastrophically in async programs because thousands of interleaved coroutines run on the same OS thread. Python's `contextvars` module provides coroutine-local state that isolates context trees across concurrent tasks 🧬🛡️.
import asyncio
import contextvars
# Define coroutine-isolated variable:
trace_id = contextvars.ContextVar("trace_id", default="NO_TRACE")
async def service(tid):
trace_id.set(tid)
await asyncio.sleep(0.01)
# Value remains isolated to this task:
print(f"Service running for: {trace_id.get()} 🚀")
async def main():
await asyncio.gather(service("TX_101"), service("TX_202"))
asyncio.run(main())
# 24. Context Variables in Async Coroutines with contextvars In synchronous web frameworks like legacy Flask or Django, developers store current request metadata, authentication tokens, and trace IDs inside `threading.local()`. In asynchronous architectures, that pattern corrupts data instantly 🛑. ```python import contextvars request_context = contextvars.ContextVar("req", default=None) ``` ### How contextvars Operates 1. **Thread Sharing vs Context Isolation**: In `asyncio`, 10,000 tasks run on a single OS thread. `contextvars` hooks into CPython's execution context, maintaining an immutable copy-on-write HAMT (Hash Array Mapped Trie) for each task 🧬. 2. **Context Inheritance**: When `asyncio.create_task()` is called, it snapshots the parent coroutine's current context. Changes made inside the child task do not bleed backward into the parent or horizontally into sibling tasks. 3. **Reset Tokens**: Calling `.set()` returns a `Token`. You can restore previous values via `.reset(token)`, essential for middleware pipelines 🛡️. --- ### Interactive Pop-Quiz 🧠 #### Why can you not use `threading.local` to store per-request state in an asyncio server? - [ ] Because all coroutines on the same thread would overwrite each other's state simultaneously 💥 - [ ] Because `threading.local` requires Python to run in 32-bit mode - [ ] Because the `asyncio` loop throws a TypeError whenever a thread object is inspected - [ ] Because `threading.local` automatically encrypts keys with DES --- ### Practical Challenge 🎯 Define a `contextvars.ContextVar` named `session_user` with default `'ANON'`. Create an async function `login(username)` that sets the context variable, sleeps 0.01s, and returns `session_user.get()`. Spawn two concurrent tasks with `'alice'` and `'bob'`, and print both returned usernames. <details> <summary>Solution</summary> ```python import asyncio import contextvars session_user = contextvars.ContextVar("session_user", default="ANON") async def login(username): session_user.set(username) await asyncio.sleep(0.01) return session_user.get() async def main(): t1 = asyncio.create_task(login("alice")) t2 = asyncio.create_task(login("bob")) r1, r2 = await asyncio.gather(t1, t2) print(f"{r1},{r2}") asyncio.run(main()) ``` </details>