On this page
  1. contextvars
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Isolated Per-Task State in asyncio
  7. Gotchas & Boundaries
  8. Common Functions
  9. Classes & Objects

contextvars

Prev: contextlib | Up: stdlib_module | Next: copy
Rel: os, io, time, argparse, getopt
Ref: docs.python.org — contextvars
Tags: #public #python3 #stdlib


Import

import contextvars

Overview

Context-local variables (ContextVar, copy_context) that work seamlessly across both asyncio tasks and threading threads—the modern async-safe replacement for threading.local(). Ideal for propagating per-request correlation IDs, active user/tenant metadata, or scoped configuration without threading arguments through every function signature.

Quick Start

from contextvars import ContextVar

request_id: ContextVar[str] = ContextVar("request_id", default="none")
assert request_id.get() == "none"

token = request_id.set("req-123")
try:
    assert request_id.get() == "req-123"
finally:
    request_id.reset(token)
assert request_id.get() == "none"

Implementation Walkthrough

1. Isolated Per-Task State in asyncio

Each asyncio.Task automatically receives a shallow copy of the current context, so concurrent requests never clobber each other's ContextVar:

import asyncio
from contextvars import ContextVar

current_user: ContextVar[str] = ContextVar("current_user")

async def handle(user: str) -> str:
    current_user.set(user)
    await asyncio.sleep(0.01)
    return current_user.get()

async def main() -> list[str]:
    async with asyncio.TaskGroup() as tg:
        t1 = tg.create_task(handle("ada"))
        t2 = tg.create_task(handle("grace"))
    return [t1.result(), t2.result()]

assert asyncio.run(main()) == ["ada", "grace"]

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes