示例工程 20-taskgroup-cancellation-contextvars
20-taskgroup-cancellation-contextvars/04-contextvars-isolation/contextvars_isolation.py
"""演示 contextvars 在协程任务之间的隔离。"""
from __future__ import annotations
import asyncio
from contextvars import ContextVar
request_id: ContextVar[str] = ContextVar("request_id", default="none")
async def handle(name: str, delay: float, results: list[tuple[str, str]]) -> None:
request_id.set(name)
await asyncio.sleep(delay)
results.append((name, request_id.get()))
async def run() -> tuple[list[tuple[str, str]], str]:
results: list[tuple[str, str]] = []
await asyncio.gather(
handle("a", 0.02, results),
handle("b", 0.01, results),
)
return sorted(results), request_id.get()
async def main() -> None:
results, parent = await run()
print(f"results: {results}")
print(f"parent: {parent}")
if __name__ == "__main__":
asyncio.run(main())