Lesson 18 of 20 · 15m
contextvars and Context Managers: State That Follows the Task
ContextVar gives each asyncio task its own value where threading.local can't, and __exit__ suppression plus yield-in-try/finally decide whether cleanup actually runs.
threading.local() gives each thread its own values. asyncio puts a thousand tasks on one thread, which collapses threading.local into a single shared slot — every task sees every other task's "request ID". The mechanism that survives the event loop is contextvars.ContextVar: per-context state, and a Task is a context.
import contextvars
request_id = contextvars.ContextVar("request_id")
token = request_id.set("req-42")
try:
handle() # every get() in this context sees req-42
finally:
request_id.reset(token)var.set(v) returns a Token; reset(token) restores the previous value — put it in finally, or the value leaks into whatever reuses the context next (a long-lived main task will hold a stale ID for the rest of the process). var.get(default) raises LookupError when unset and no default was declared, so declare one or pass one.
Contexts copy shallowly: a set() binds a name, and the binding is what the copy isolates. set() a mutable dict and mutations inside the child are visible to the parent — the isolation boundary is the variable slot, not the object.
How it reaches the task
When asyncio creates a Task it snapshots the current context with copy_context() and runs the coroutine inside that copy. set() inside a child task is invisible to its parent and siblings — the copy is the scope, not the variable. loop.run_in_executor wraps the callable in the same snapshot, so context vars propagate into worker threads: a request ID logged from inside an asyncio.to_thread call resolves correctly, which is precisely what a thread-local cannot do — the worker is a different thread, but the context followed the call.
None of this is async-only. PEP 567 added contextvars in 3.7 for a reason broader than asyncio — decimal.Context arithmetic state is the classic sync example of "ambient settings that should follow the operation". You can run a function in an explicit context with copy_context().run(fn) — useful in tests, where asserting on a ContextVar your middleware sets requires entering the context yourself.
Who already runs on it
structlog's bind_contextvars and merge_contextvars are the standard recipe for "request ID in every log line" without threading the ID through fifty function signatures. sentry-sdk holds its scope in a ContextVar so concurrent requests don't bleed breadcrumbs into each other's events. OpenTelemetry's context propagation is contextvars underneath — a span opened in ASGI middleware is found by the handler three awaits later because both run in the copied context. The "middleware sets it, anything downstream reads it" pattern is ContextVar — not a global, not a thread-local, not a request object passed by hand.
Context managers are the cleanup half
with is a protocol: __enter__ runs, then __exit__(exc_type, exc, tb) runs always — and if __exit__ returns True the exception is swallowed. That suppression is the loaded part. contextlib.suppress(ValueError) says it out loud; a hand-rolled __exit__ that returns True accidentally hides the error it was supposed to report. If you write __exit__, the honest return is None — let exceptions propagate unless suppressing is the entire point.
@contextmanager carries the same trap inverted. The generator's code after yield only runs when control resumes — an exception thrown into the with body lands at the yield statement, and anything after it is skipped unless you wrap the yield:
@contextmanager
def timer(name):
t = time.monotonic()
try:
yield
finally:
log(name, time.monotonic() - t)ExitStack handles the variable case: stack.enter_context(cm) in a loop for resources you don't know at write time, stack.callback(fn) for plain functions, AsyncExitStack plus contextlib.aclosing when async generators need a guaranteed aclose().
The practice
ContextVar plus token plus reset in finally for anything scoped to "the current operation" — request IDs, tenant IDs, auth context. Never return True from __exit__ unless suppression is the point. yield inside try/finally in every @contextmanager. Globals are for constants; context vars are for what is currently happening.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
Free-Threaded Python, Measured: Threads Finally Scale, and Your Unlocked Counter Finally Breaks
Python 3.14 made the no-GIL build officially supported, and 3.15 kept going. I ran the same CPU-bound job on standard and free-threaded builds of both: threads went from slower-than-serial to 1.9x faster, and a counter that never lost an update under the GIL lost 70% of them without it.
What is Python? Enterprise, Data Science, and the Backend of the Web
Python runs Instagram, Dropbox, Netflix, Spotify, and Reddit. It trains the models that power modern AI. It processes petabytes of data in enterprise pipelines. And I ignored it for years because I thought it was just for academics. Here is what changed my mind.
What Python 3.13 Shipped
The first release of Python 3.13 is now here as a Beta Release. This article is a rundown of all of the important changes and features that are being released in Python 3.13, along with what they mean for Python Developers. Please remember that this can change between
What Python 3.11 Actually Changed
The Python Programming Language releases a new version every year, with a feature-locked beta release in the first half of the year and the final release toward the end of the year. The feature set for Python 3.11 has just been finalized, with a beta version available for testing.