Python AsyncIO Patterns Cheat Sheet

Orchestrate tasks, cancellations, and context safely

Structured concurrency, cancellation shielding, and context propagation for asyncio code Quick reference guide with examples and best practices. Updated November 2025.

Last Updated: November 21, 2025

Focus Areas

Pattern Why it matters
TaskGroup Structured concurrency that cancels all children together.
shield() Protect cleanup from being canceled with the caller.
contextvars Pass request-scoped data without relying on globals.
asyncio.run() Create and close an event loop in scripts safely.

Key APIs

asyncio.create_task(coro)
Launch a background unit of work while the parent continues.
asyncio.TaskGroup()
`async with TaskGroup()` keeps child tasks scoped together.
await asyncio.wait_for(task, timeout=5)
Enforce deadlines and handle TimeoutError.
await asyncio.shield(cleanup())
Let cleanup finish even if the surrounding task cancels.

Summary

Favor TaskGroup/async context managers for predictable cleanup, add shielding when canceling, and propagate metadata through context variables.

💡 Pro Tip: Use TaskGroup/async context managers so canceled parents always wait for their children.
← Back to Programming Languages | Browse all categories | View all cheat sheets