Per-Task State Without Globals? Python's contextvars
This article explains how Python's contextvars gives each asyncio task its own value of a variable, how contexts are copied between tasks, threads and executors, and which errors come from mutable values and tokens.
Code that serves many requests at once often needs a value that belongs to the current request, such as an identifier for the logs or the active user, without passing it as an argument through every function. The present article addresses the module contextvars, introduced in Python 3.7 by PEP 567, which provides variables whose value depends on the execution context in which they are read. Split-screen cooperative games provide an appropriate image: two players share one console and one game, yet each half of the screen shows its own player's health and inventory. This means that several asyncio tasks running on the same thread can read the same context variable and each obtain its own value, which a global variable or a thread-local cannot offer. The analogy, however, stops at this point, because each player keeps a fixed half, whereas a new task starts with a copy of its creator's values, and any change it makes never flows back to the creator. The article compares context variables with thread-locals, explains how contexts are copied between tasks and threads, and identifies the errors of tokens and mutable values. Giving each concurrent task its own view of shared names, without threading them through every call, is the secret weapon of contextvars.
Why Thread-Locals Fail in Asynchronous Code
threading.local gives each thread its own attributes, which suffices when every request runs in a thread of its own. An event loop, however, runs many tasks on one thread, interleaving them at each await, so a thread-local value written by one task is overwritten by the next. The following example stores a request name both ways and reads it after a suspension.
import asyncio
import contextvars
import threading
request_id = contextvars.ContextVar("request_id", default="unknown")
local = threading.local()
async def handle(name):
request_id.set(name)
local.name = name
await asyncio.sleep(0.01)
return request_id.get(), local.name
async def main():
print(await asyncio.gather(handle("A"), handle("B")))
asyncio.run(main())
# Output: [('A', 'B'), ('B', 'B')]
After the pause, each task still reads its own identifier from the context variable, whereas the thread-local holds B for both, because the second task overwrote the attribute shared by the only thread. The module therefore complements the synchronization primitives examined in the article devoted to thread synchronization: instead of coordinating access to shared state, it gives each task its own.
How Contexts Are Copied
A context is a mapping from context variables to values, and every task created by asyncio runs in a copy of the context that was current when it was created; the copy is cheap, because contexts are immutable structures that share their contents. Consequently, a task sees the values of its creator, but its own set calls remain inside its copy. Threads follow a different rule, as the following example shows.
import asyncio
import contextvars
import threading
request_id = contextvars.ContextVar("request_id", default="unknown")
def log(message):
return f"[{request_id.get()}] {message}"
async def main():
request_id.set("parent")
async def child():
request_id.set("child")
return log("inside")
print(await asyncio.create_task(child())) # Output: [child] inside
print(log("after")) # Output: [parent] after
print(await asyncio.to_thread(log, "thread")) # Output: [parent] thread
loop = asyncio.get_running_loop()
print(await loop.run_in_executor(None, log, "executor")) # Output: [unknown] executor
asyncio.run(main())
request_id.set("main")
results = []
worker = threading.Thread(target=lambda: results.append(log("plain thread")))
worker.start()
worker.join()
print(results) # Output: ['[unknown] plain thread']
ctx = contextvars.copy_context()
print(ctx.run(log, "explicit")) # Output: [main] explicit
The function log obtains the identifier without receiving it as an argument. The child's change does not reach the parent, asyncio.to_thread carries the caller's context into the worker thread, whereas run_in_executor and a plain threading.Thread start with an empty context on the default build. Python 3.14 adds a context parameter to Thread, and on the free-threaded build new threads copy the caller's context by default; copy_context with Context.run remains the explicit way to run a function inside a chosen context. The choice between tasks, threads and processes is examined in the article devoted to concurrency models.
Pitfalls of Context Variables
A context variable behaves like a global whose value depends on an invisible copy, so most errors come from expecting that copy to be shared, or from misusing the tokens that restore previous values. Six pitfalls are distinguished, which are the following:
- Mutable values are shared. The context stores a reference, so a list given as
defaultor set before creating tasks is modified by all of them. - Changes do not flow back. A value set inside a task or callback is lost for the code that created it.
- Executors and threads.
run_in_executorand, on the default build,threading.Threaddo not carry the context unless it is passed explicitly. - Token misuse. A token can reset its variable only once, only for the variable that created it and only in the same context; otherwise
RuntimeErrororValueErroris raised. - No default.
get()on a variable without a default, never set in the current context, raisesLookupError. - Hidden dependencies. A function that reads a context variable depends on state that its signature does not show, which makes it harder to test and reuse.
The first, fourth and fifth pitfalls are reproduced in the following example.
import asyncio
import contextvars
cart = contextvars.ContextVar("cart", default=[])
async def add(item):
cart.get().append(item)
async def main():
await asyncio.gather(add("book"), add("pen"))
print(cart.get()) # Output: ['book', 'pen']
asyncio.run(main())
user = contextvars.ContextVar("user")
token = user.set("ada")
user.reset(token)
try:
user.reset(token)
except RuntimeError:
print("token already used") # Output: token already used
inner = contextvars.copy_context().run(user.set, "grace")
try:
user.reset(inner)
except ValueError:
print("token from another context") # Output: token from another context
try:
user.get()
except LookupError:
print("no value and no default") # Output: no value and no default
The two tasks appended to the same list, because each copy of the context referred to the one default object; a per-task collection must be created and set inside each task. In Python 3.14 the token returned by set is also a context manager, so with user.set("ada"): restores the previous value automatically at the end of the block, the protocol described in the article devoted to context managers. Reading a context variable cost about 12 nanoseconds on CPython 3.12, so the mechanism adds no measurable overhead to ordinary code.
Choosing Where to Keep Per-Request State
Consequently, context variables suit values that must follow a request through asynchronous code without appearing in every signature, as the following table summarizes.
| Situation | Recommended approach |
|---|---|
Request identifiers, locale or current user in asyncio code |
contextvars.ContextVar |
| State per thread in purely threaded code | threading.local, or a context variable |
| Carrying the context into a thread pool | asyncio.to_thread, or copy_context().run |
| Temporary value restored at the end of a block | set and reset in try/finally, or with var.set(...) since 3.14 |
| Data that one function needs from its caller | An ordinary argument |
| State that tasks must share and modify | A shared object with explicit synchronization |
Conclusion
It is concluded that a ContextVar holds one value per execution context, that every asyncio task runs in a copy of its creator's context, and that tokens restore earlier values in a controlled way. This magic relies on copies: mutable values remain shared, changes never return to the creator, and threads and executors receive a context only when it is passed to them. Grouping a few attributes into a lightweight object without defining a class is the purpose of types.SimpleNamespace, which is developed in a future article of this series.