Context Variables

2.4 · active · verified Sat Apr 11

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.

Warnings

Install

Imports

Quickstart

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())

view raw JSON →