On this page
contextvars
Prev: contextlib | Up: stdlib_module | Next: copy
Rel: os, io, time, argparse, getopt
Ref: docs.python.org — contextvars
Tags: #public #python3 #stdlib
Import
import contextvars
Overview
Context-local variables (ContextVar, copy_context) that work seamlessly across both asyncio tasks and threading threads—the modern async-safe replacement for threading.local(). Ideal for propagating per-request correlation IDs, active user/tenant metadata, or scoped configuration without threading arguments through every function signature.
Quick Start
from contextvars import ContextVar
request_id: ContextVar[str] = ContextVar("request_id", default="none")
assert request_id.get() == "none"
token = request_id.set("req-123")
try:
assert request_id.get() == "req-123"
finally:
request_id.reset(token)
assert request_id.get() == "none"
Implementation Walkthrough
1. Isolated Per-Task State in asyncio
Each asyncio.Task automatically receives a shallow copy of the current context, so concurrent requests never clobber each other's ContextVar:
import asyncio
from contextvars import ContextVar
current_user: ContextVar[str] = ContextVar("current_user")
async def handle(user: str) -> str:
current_user.set(user)
await asyncio.sleep(0.01)
return current_user.get()
async def main() -> list[str]:
async with asyncio.TaskGroup() as tg:
t1 = tg.create_task(handle("ada"))
t2 = tg.create_task(handle("grace"))
return [t1.result(), t2.result()]
assert asyncio.run(main()) == ["ada", "grace"]
Gotchas & Boundaries
- Declare
ContextVarat module top level, not inside closures or loops: Creating newContextVarinstances repeatedly can retain references in contexts. - Always restore with
var.reset(token)in afinally:block when overriding a value temporarily in the same task. - Never store a mutable default (
default=[]): All tasks would share the exact same list; default toNoneor an immutable tuple instead. - Calling
get()without a default raisesLookupErroruntil.set()has been called in that context.
Common Functions
- contextvars.copy_context() —
copy_context()—contextvars.copy_context()function.
Classes & Objects
- contextvars.Context —
contextvars.Contextclass. (Methods:.copy(),.get(),.items(),.keys(),.run(),.values()) - contextvars.ContextVar —
contextvars.ContextVarclass. (Methods:.get(),.reset(),.set()) - contextvars.Token —
contextvars.Tokenclass.
Linked from
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/contextlib
- tuts/python3/stdlib_module/contextvars/Context
- tuts/python3/stdlib_module/contextvars/ContextVar
- tuts/python3/stdlib_module/contextvars/copy_context
- tuts/python3/stdlib_module/contextvars/Token
- tuts/python3/stdlib_module/copy
- tuts/python3/stdlib_module/stdlib_module
Related notes
- tuts/python3/stdlib_module/contextlib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/contextvars/Context Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/contextvars/ContextVar Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/contextvars/copy_context Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/contextvars/Token Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/copy Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/argparse Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/asyncio Linked here; shared tags: #stdlib