Featureadvanced
Context variables
Also called contextvars, ContextVar, copy_context, Context.run, context-local state, Token, PEP 567.
A contextvars.ContextVar holds a value per context. Each asyncio task runs in a copy of the context that created it, so a value set in one task does not leak into another task in the same thread.
- Language
- Python
- Proposals
- pep-567
Synopsis
import asyncio
from contextvars import ContextVar
request_id = ContextVar("request_id", default="none")
def log(message):
print(f"[{request_id.get()}] {message}")
async def handle(rid):
request_id.set(rid)
await asyncio.sleep(0)
log("done")
async def main():
async with asyncio.TaskGroup() as tg:
tg.create_task(handle("a"))
tg.create_task(handle("b"))
log("main")
asyncio.run(main())
[a] done
[b] done
[none] main
Semantics
r1. ContextVar(name, default=...) declares a context variable. get() returns the value in the current context. If there is no value, it returns the default argument of get(), or else the default of the variable, or else it raises LookupError.1 Example: no-default.
r2. set(value) "Returns a Token object that can be used to restore the variable to its previous value via the ContextVar.reset() method."1 The token is also a context manager that calls reset() at the end of the block. Example: token.
r3. "Any changes to ContextVar values via the ContextVar.set() method are recorded in the current context." Context.run(callable) "Enters the Context, executes callable(*args, **kwargs), then exits the Context."1 Example: run-in-copy.
r4. "If no context is provided, the Task copies the current context and later runs its coroutine in the copied context."2 So a set() in a task does not change the value in the code that created the task. Example: per-task.
r5. "Each thread has its own effective stack of Context objects."1 A new threading.Thread starts with a copy of the context of the caller of start() only if sys.flags.thread_inherit_context is true. "The flag defaults true on free-threaded builds and false otherwise."3 Pass context= to choose. Example: thread-context.
r6. asyncio.to_thread() is different: "the current contextvars.Context is propagated, allowing context variables from the event loop thread to be accessed in the separate thread."2
r7. "Context Variables should be created at the top module level and never in closures."1 A context holds strong references to its variables, so a variable made in a function is not freed.
Examples
from contextvars import ContextVar
level = ContextVar("level", default=0)
with level.set(1):
print(level.get())
token = level.set(2)
print(level.get())
level.reset(token)
print(level.get())
print(level.get())
1
2
1
0
from contextvars import ContextVar, copy_context
user = ContextVar("user")
user.set("ann")
ctx = copy_context()
def change():
user.set("bob")
return user.get()
print(ctx.run(change))
print(user.get())
print(ctx[user])
bob
ann
bob
The change happened in ctx, not in the current context (rule r3).
import threading
from contextvars import ContextVar, Context, copy_context
color = ContextVar("color", default="none")
color.set("red")
def show(label):
print(label, color.get())
t = threading.Thread(target=show, args=("copy:",), context=copy_context())
t.start(); t.join()
t = threading.Thread(target=show, args=("empty:",), context=Context())
t.start(); t.join()
copy: red
empty: none
With an explicit context=, the result is the same on both builds (rule r5).
Versions
Since 3.7
The
contextvarsmodule was added by PEP 567, and asyncio tasks run in a copy of the context.12
Since 3.14
A token works as a context manager, and
threading.Threadtakes acontextargument.13
Pitfalls
This code raises LookupError, on purpose.
from contextvars import ContextVar
user = ContextVar("user")
print(user.get())
The variable has no default and no value, so get() raises LookupError (rule r1).
This code runs but gives a wrong answer on purpose.
import asyncio
from contextvars import ContextVar
total = ContextVar("total", default=0)
async def add(n):
total.set(total.get() + n)
async def main():
await asyncio.create_task(add(5))
print(total.get())
asyncio.run(main())
0
The task changed its own copy of the context, not the context of main() (rule r4). Return the value from the task instead.
Comparison
threading.local() gives one value per thread. A context variable gives one value per context, so it also separates asyncio tasks that share one thread. PEP 567 says: "Thread-local variables are insufficient for asynchronous tasks that execute concurrently in the same OS thread."4 See Multi-threading and The asyncio module.
References
- contextvars — Context Variables, Python 3.15 documentation, Context Variables; Manual Context Management; asyncio support
- Coroutines and Tasks, Python 3.15 documentation, Task; to_thread
- threading — Thread-based parallelism, Python 3.15 documentation, Thread
- PEP 567: Context Variables, Rationale; Specification
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 9DM5K0 Edit this page History Report an error Markdown