aiocontextvars provides asyncio support for the PEP-567 contextvars backport, effectively offering 'task local' storage similar to 'threading.local' but scoped to asyncio tasks. It is primarily relevant for Python versions 3.5 and 3.6, as Python 3.7 and later include native `contextvars` support. The project is currently at version 0.2.2 and is explicitly marked for deprecation once native asyncio contextvars support is fully stable in older backports.
pip install aiocontextvarsVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates defining and using a `ContextVar` within an asyncio application. It shows how values set in a parent task are inherited by child tasks upon creation, and how to set and retrieve values using `ContextVar.set()` and `ContextVar.get()`. `ContextVar.reset()` is used with the token returned by `set()` to restore previous context.
Upgrade to Python 3.7+ and use `import contextvars` directly. For Python 3.5/3.6, continue using `aiocontextvars` but be aware of its maintenance status.
Update code to use `ContextVar.set()` with `token = var.set(value)` and later `var.reset(token)`. Remove calls to deprecated `delete()`, `enable_inherit()`, and `disable_inherit()`.
Ensure `import aiocontextvars` is one of the first lines of code executed in your application's entry point.
Design your application with this snapshot behavior in mind. If you need dynamic updates across tasks, consider passing data explicitly or using other synchronization primitives.
Wrap your callable with `copy_context().run`. Example: `loop.call_soon(copy_context().run, my_method)`.
Ensure `var.set(value)` is called at least once in the current context (or a parent context if inherited) before calling `var.get()`. You can also provide a default value when initializing the `ContextVar`: `my_variable = ContextVar('my_variable', default='initial_value')`.Replace `var.delete()` with `var.reset(token)` where `token` was the result of the `var.set()` call you wish to revert. If no token is available, you cannot 'delete' a value, only reset to a prior state.
Always use public `asyncio` APIs (e.g., `asyncio.run()`, `asyncio.create_task()`, `asyncio.get_event_loop()`) and ensure `aiocontextvars` is imported at startup. If using `uvloop`, consider if `aiocontextvars` is the right solution, as `uvloop` might need specific integration not provided by this library.