Context Variable (contextvars)
say it: “KON-tekst VAIR-ee-uh-bul” /ˈkɑntɛkst ˈvɛəriəbəl/ or “KON-tekst-varz” /ˈkɑntɛkstˌvɑrz/
A value that belongs to the current task, so async tasks do not mix up values.
What is a context variable?
A context variable holds a value that belongs to the current task, like "which user is this request for", so async tasks running at the same time don't mix up each other's values.
import asyncio
from contextvars import ContextVar
current_user = ContextVar("current_user")
async def handle(user):
current_user.set(user)
await asyncio.sleep(0.1)
print("Serving", current_user.get()) # always the right user
async def main():
await asyncio.gather(handle("Ana"), handle("Ben"))
asyncio.run(main())
Level: Master · More Python terms at this level
Updated