Isolate Request Context with ContextVar
Core idea
ContextVar stores a binding local to the current context. asyncio tasks normally copy the creating context at task creation, so different tasks can set different request IDs. set returns a token; reset(token) restores the previous binding in Python 3.13. Context copying is shallow: mutable values may still be shared.
import asyncio
async def main(): from contextvars import ContextVar request=ContextVar('request',default='root') async def handle(label): token=request.set(label) try: await asyncio.sleep(0) return request.get() finally: request.reset(token) print(await asyncio.gather(handle('A'),handle('B'))) print(request.get())
asyncio.run(main())Each task sees its own binding while the parent remains unchanged.
Expected output:
['A', 'B']rootRestore the prior binding
import asyncio
async def main(): from contextvars import ContextVar mode=ContextVar('mode',default='normal') token=mode.set('audit') try: print(mode.get()) finally: mode.reset(token) print(mode.get())
asyncio.run(main())Reset uses the token rather than guessing the previous value.
Expected output:
auditnormalCommon mistake
Create ContextVar objects at module scope in production; contexts retain references to them. Do not store a mutable dictionary and assume each task gets a deep copy. A token must be reset in the context that created it.
Practice
Set a parent label, create a task, change the parent label before awaiting the task, and inspect which label the task inherited.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Context variables
Check your understanding of context variables.
What is printed?
import asyncio
async def main(): from contextvars import ContextVar x=ContextVar('x',default=1) t=x.set(2); x.reset(t) print(x.get())
asyncio.run(main())What is printed?
import asyncio
async def main(): from contextvars import ContextVar x=ContextVar('x',default='a') async def f(): return x.get() t=asyncio.create_task(f()) x.set('b') print(await t)
asyncio.run(main())Does context copying deep-copy mutable values?
What restores a previous ContextVar binding?