contextvars.ContextVar()
contextvars.ContextVar() is a Python function in the ContextVars Module category. Creates a context variable that has separate values in different async contexts. The syntax is contextvars.ContextVar(name, *, default=_NO_DEFAULT). Returns: ContextVar object. A typical example: from contextvars import ContextVar
user_id = ContextVar("user_id", default=0)
async def handle_request():
user_id.set(42)
await process()
async def process():
print(user_id.get()) # 42 (context propagated). A close sibling is ContextVar.get(), which returns the value of the context variable for the current context. A close sibling is ContextVar.set(), which sets the value of the context variable for the current context. A close sibling is ContextVar.reset(), which resets the context variable to its previous value using the token from set(). A close sibling is contextvars.copy_context(), which returns a copy of the current context (all context variables and their values). More about this category: Context variables for async — ContextVar, copy_context, Context. Related ContextVars Module entries: ContextVar.get(), ContextVar.set(), ContextVar.reset(), contextvars.copy_context().