Runtime and Context Modules

contextvars

Context-local bindings support isolated state across asynchronous tasks and threads. ContextVar.set returns a token for restoring the previous binding; copy_context copies bindings, not nested mutable values. Avoid using a shared mutable default as task-local storage.

Formal Syntax & Structure

python syntaxpython
import contextvars

Return Value

module

Module namespace available through import; import is a statement, not a value-returning expression.

Working Example

Example Snippetpython
from contextvars import ContextVarrequest = ContextVar("request", default="none")token = request.set("demo")print(request.get())request.reset(token)print(request.get())
Python Reference