Python's standard library module for context-local state — like thread-local variables but works correctly across asyncio tasks, where threading.local() doesn't.
contextvars.ContextVar lets you store per-coroutine or per-thread state that propagates through nested function calls without explicit argument passing. The classic use case is request-scoped data (request ID, user, locale) in async web frameworks. Each asyncio task gets its own copy of the context; setting a value in one task doesn't leak to others. This is the modern replacement for threading.local in async code.
Storing the current request ID in a contextvar so every log statement, database query, and downstream HTTP call can include it without threading it through every function signature.
contextvars are the right primitive for cross-cutting concerns (logging, tracing, multi-tenancy) in async Python — failing to use them in asyncio leads to subtle state-leakage bugs.
Need help implementing this in your business?
Get Started