Registry / observability / contextvars

contextvars

JSON →
library2.4pypypi✓ verified 27d ago

The `contextvars` library is a backport of the standard library `contextvars` module (introduced in Python 3.7 via PEP 567), providing APIs to manage, store, and access context-local state. It enables task-local variables in asynchronous code, ensuring data isolation across different coroutines or threads without explicit argument passing. The current version is 2.4, and it typically releases on demand for bug fixes or dependency updates.

pip install contextvars
INSTALL
IMPORT
SIG · CONTEXTVARS
C
contextvars
observabilitypythonv2.4
Install
2.4s avg
Import
—
Disk
17MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.9–3.13
musl
3.9–3.13
Install & Compatibility
Where this runs
tested against v2.4 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.000s · 19.5MB
glibc
py 3.10–3.95 runs
installs and imports cleanly · install 2.4s · import 0.000s · 20MB
17MB installed
● package 17MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

ContextVar
✓ from contextvars import ContextVar
copy_context
✓ from contextvars import copy_context
current_context
✓ from contextvars import current_context
Used to retrieve the current Context object as a mapping.
Token
✓ from contextvars import Token
An opaque object returned by `ContextVar.set()` and required by `ContextVar.reset()` to revert a variable to its previous state.

This example demonstrates how `ContextVar` isolates state in asynchronous tasks. Each `handle_request` coroutine sets a `current_user` value, which remains local to its execution context, preventing state bleeding between concurrent tasks. The `token` returned by `set()` is crucial for `reset()`ing the variable to its previous state, often done in a `try-finally` block for proper cleanup.

import asyncio import contextvars # Define a context variable current_user = contextvars.ContextVar('current_user', default='Guest') async def handle_request(user_name): # Set the user for the current task. This returns a Token. token = current_user.set(user_name) try: print(f"Task for {user_name}: Currently handled by {current_user.get()}") await asyncio.sleep(0.1) # Simulate async work print(f"Task for {user_name}: Still handled by {current_user.get()}") finally: # Reset the context variable to its previous value using the token current_user.reset(token) async def main(): print(f"Before tasks: {current_user.get()}") await asyncio.gather( handle_request("Alice"), handle_request("Bob") ) print(f"After tasks: {current_user.get()}") # Should revert to default if __name__ == '__main__': asyncio.run(main())
Debug
Known issues
gotchaCreating `ContextVar` instances within closures or functions repeatedly (e.g., inside a loop or request handler) can lead to memory leaks in long-running applications. Each call creates a new `ContextVar` object that may persist in the context graph.
fix
Always declare `ContextVar` instances at the module level or as class attributes to ensure a single instance is created per application lifetime.
affects: All
gotchaCalling `ContextVar.reset(token)` with a token that was created in a different `Context` will raise a `ValueError`. Additionally, a `RuntimeError` is raised if a token is used to reset a variable more than once.
fix
Ensure `reset(token)` is called in the same `Context` where its corresponding `set()` operation occurred and that each token is used only once. Using `try-finally` blocks or `contextlib.contextmanager` is a common pattern to manage `set`/`reset` pairs safely.
affects: All
gotchaForgetting to `reset()` a `ContextVar` after `set()` in long-running applications (e.g., web servers, background workers) can lead to state bleeding, where subsequent tasks inherit an unexpected context value. This is a common source of hard-to-debug issues.
fix
Always pair `ContextVar.set()` with `ContextVar.reset(token)` in a `try-finally` block to guarantee the context is restored, even if exceptions occur. Python 3.14+ `Token` objects support the context manager protocol for automatic reset.
affects: All
gotchaAttempting to get the value of a `ContextVar` using `ContextVar.get()` when no value has been set in the current context and no `default` value was provided during `ContextVar` instantiation will raise a `LookupError`.
fix
Always provide a `default` value when creating a `ContextVar` if a value isn't guaranteed to be set, or wrap `ContextVar.get()` calls in `try-except LookupError` blocks. Alternatively, `ContextVar.get(default_value_for_this_call)` can be used.
affects: All
gotchaContexts are not automatically propagated across process boundaries. If `contextvars` are used with `multiprocessing.ProcessPoolExecutor`, changes made in a worker process's context will not affect the main process's context or other worker processes, as context variables are copied (pickled) when tasks are assigned.
fix
Avoid using `contextvars` for sharing state directly between `ProcessPoolExecutor` processes. Instead, use multiprocessing primitives (e.g., `Queue`, `Pipe`, `shared_memory`) for inter-process communication if state needs to be truly shared or synchronized.
affects: All
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'contextvars'
This error typically occurs when the `contextvars` backport library is not installed in a Python environment older than 3.7, or if the Python interpreter itself is corrupted or incorrectly installed, especially in virtual environments.
fix
If using Python < 3.7, install the backport: `pip install contextvars`. If on Python 3.7+ and still encountering the error, ensure your Python installation or virtual environment is not corrupted, or check for issues with the underlying `_contextvars` C module.
LookupError: <ContextVar name='...' at 0x...> is not set
This `LookupError` is raised when `ContextVar.get()` is called to retrieve a value, but no value has been set for that `ContextVar` in the current context, and no default value was provided during the `ContextVar`'s creation or to the `get()` method itself.
fix
Provide a default value when creating the `ContextVar` (e.g., `my_var = ContextVar('my_var', default='default_value')`) or when calling `get()` (e.g., `my_var.get('fallback_value')`). Alternatively, ensure `ContextVar.set()` is called before `get()` in the relevant execution context.
ValueError: <Token var=<ContextVar name='...' default='...' at 0x...>> was created in a different Context.
This error occurs when attempting to reset a `ContextVar` using a `Token` that was created by a `ContextVar.set()` call in a different execution context. This can happen in asynchronous frameworks like FastAPI if synchronous dependencies are run in separate threads, causing context boundaries to be crossed.
fix
Ensure that `ContextVar.set()` and `ContextVar.reset(token)` calls are made within the same execution context. If using frameworks that run parts of your code in different threads/tasks (e.g., FastAPI's sync dependencies), be mindful that contextvars do not automatically propagate changes back across thread boundaries. Re-evaluate if `contextvars` are the appropriate mechanism for cross-thread communication in such scenarios.
RuntimeError: cannot reset context variable '...' to ...: token was already used once
This `RuntimeError` is raised when `ContextVar.reset(token)` is called with a `Token` object that has already been used to reset the `ContextVar`. Each token is single-use for resetting purposes.
fix
A `Token` returned by `ContextVar.set()` can only be used once with `ContextVar.reset()`. Ensure that you are not attempting to reset the variable multiple times with the same token. If you need to manage context changes, use `try...finally` blocks with `set()` and `reset(token)` to ensure proper cleanup, or consider using tokens as context managers (Python 3.14+).
TypeError: contextvars.Context.run() missing 1 required positional argument: 'callable'
The `Context.run()` method expects a callable (a function or method) as its first argument, along with any arguments for that callable. This error indicates that `callable` was not provided or was provided incorrectly.
fix
Pass a function or other callable object as the first argument to `Context.run()`, followed by any arguments the callable needs. For example: `ctx.run(my_function, arg1, arg2)`.
Upgrade
Version history
2.4latest on PyPI · released Apr 1, 2019
Audit
Dependencies
immutablesrequiredProvides the underlying Hash Array Mapped Trie (HAMT) data structure for efficient immutable context storage. As of `contextvars` v2.4, `immutables` requires Python >=3.8.0, making this package effectively for Python 3.8+ environments where the standard library module might not be available or suitable.
Agent activity
24 hits · last 30 days
node
20
OpenAI (training)
1
Resources