aiocontextvars

0.2.2 · deprecated · verified Thu Apr 16

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.

Common errors

Warnings

Install

Imports

Quickstart

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.

import asyncio
from aiocontextvars import ContextVar

# Define a ContextVar
my_variable = ContextVar('my_variable', default='default_value')

async def child_task(task_id):
    current_val = my_variable.get()
    print(f"Task {task_id}: Initial value in child: {current_val}")
    my_variable.set(f"value_from_task_{task_id}")
    print(f"Task {task_id}: New value set in child: {my_variable.get()}")
    await asyncio.sleep(0.1)

async def main():
    print(f"Main: Initial value: {my_variable.get()}")
    token = my_variable.set("main_context_value")
    print(f"Main: Value after set: {my_variable.get()}")

    # Spawning child tasks - they inherit the context at creation
    tasks = [
        asyncio.create_task(child_task(1)),
        asyncio.create_task(child_task(2))
    ]
    await asyncio.gather(*tasks)

    print(f"Main: Value after children complete: {my_variable.get()}")
    my_variable.reset(token)
    print(f"Main: Value after reset: {my_variable.get()}")

if __name__ == '__main__':
    # IMPORTANT: aiocontextvars must be imported BEFORE creating event loops.
    # For Python 3.5/3.6, ensure aiocontextvars is imported early in your application.
    asyncio.run(main())

view raw JSON →