capypad
0 day streak
python / expert
Snippet

Scoped State with Context Variables

Context variables (contextvars) allow data to persist within a specific execution flow. Unlike thread-local storage, they are aware of async tasks, making them ideal for storing request IDs or transaction state in web servers.

snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
import contextvars
import asyncio
 
client_id = contextvars.ContextVar("client_id")
 
async def log_operation(msg):
print(f"[Client {client_id.get()}] {msg}")
 
async def handle_request(cid):
client_id.set(cid)
await log_operation("Starting process")
 
asyncio.run(asyncio.gather(handle_request(1), handle_request(2)))
Breakdown
1
client_id = contextvars.ContextVar("client_id")
Declares a variable that provides isolated storage per asynchronous context.
2
client_id.set(cid)
Sets the value for the current task without affecting other concurrently running tasks.