Skip to main content

contextvars

contextvars provides task-local context variables (PEP 567). A ContextVar carries a value that propagates with the current context, so an asyncio task can read it without explicit threading.

Source-of-record: Lib/contextvars.py, Python/context.c, contextvars docs.

ContextVar

var = ContextVar('var', default=missing)
MethodEffect
var.get(*default)Get current value; raises LookupError if unset and no default.
var.set(value)Set; returns a Token for reset.
var.reset(token)Restore the previous value.
var.nameRead-only.

Token

AttributeMeaning
varThe variable.
old_valueValue before set, or Token.MISSING.

Context

Immutable mapping of ContextVar to value. Created via copy_context().

MethodEffect
ctx.run(callable, *args, **kw)Run with ctx activated; mutations stay inside.
ctx[var]Read.
iter(ctx) / len(ctx) / var in ctxMapping protocol.
ctx.copy() / ctx.keys() / values() / items() / get(var)Mapping ops.

copy_context()

Returns a snapshot of the current context. Used to dispatch work to threads/tasks that should inherit context.

Propagation

RuntimePropagation
asyncio.TaskCaptures copy_context() at task creation.
threading.ThreadDoes not propagate (start fresh context).
concurrent.futures.ThreadPoolExecutorInherits context for submitted tasks (3.7+).
asyncio.to_threadPropagates context.

Gopy status

AreaState
ContextVar, Token, ContextComplete; backed by HAMT (immutable map).
copy_contextComplete.
Asyncio propagationComplete.

Reference

  • CPython 3.14: contextvars.
  • Python/context.c, Python/hamt.c.
  • module/contextvars/. gopy port.
  • PEP 567.