contextvars stores context-local state. Works correctly with asyncio and threads.
1import asyncio2from contextvars import ContextVar34# Define context variable5user_var: ContextVar[str] = ContextVar("user", default="anonymous")67async def process_request(user_id):8 user_var.set(user_id) # Set for this context9 await asyncio.sleep(0.1)10 print(f"Processing for {user_var.get()}")1112async def main():13 # Each task has its own context14 await asyncio.gather(15 process_request("alice"),16 process_request("bob"),17 )18 # Output: Processing for alice, Processing for bob1920asyncio.run(main())
vs threading.local:
contextvars works with asyncio.threading.local only with threads.