asyncio
cheat sheet
Python’s asyncio at a glance: coroutines, tasks, TaskGroup, gather, timeouts, cancellation, queues, locks, threads, subprocesses, streams and debugging.
- Version
- v3.15.2
- Snippets
- 68
- Sections
- 9
Version notes · asyncio 3.15.2
- 3.15 adds
TaskGroup.cancel(): stop the remaining tasks once you have what you need. - 3.14 adds
python -m asyncio ps PID/pstree PIDto inspect a running program, plusasyncio.capture_call_graph(). - 3.14 deprecates the event loop policy system (
set_event_loop_policy…), andget_event_loop()raises if no loop is running. - 3.13 added
Queue.shutdown()and madeas_completed()an async iterator.
Run many I/O-bound jobs (HTTP calls, sockets, database queries) at once on one thread: async def functions pause at await while others make progress.
I/O concurrency
thousands of sockets, one thread
TaskGroup
structured: no orphan tasks
Timeouts
async with asyncio.timeout()
Not for CPU work
use processes for that
Quick start
import asyncioasync def fetch(n): await asyncio.sleep(1) # stands in for I/O return n * 2async def main(): async with asyncio.TaskGroup() as tg: tasks = [tg.create_task(fetch(i)) for i in range(3)] print([t.result() for t in tasks]) # ~1 s, not 3asyncio.run(main())- Define a coroutine function
- Entry point: new loop, run, close
- Wait for a coroutine (inside
async def) - Non-blocking sleep
- Yield control to other tasks
- Debug mode: slow callbacks, unawaited coroutines
- Several
runcalls on one loop - Use another loop implementation
Calling fetch(url) without await only creates a coroutine object; nothing runs. Python warns "coroutine was never awaited".
- Waits for all tasks on exit
- Start a task in the group;
t.result()after - Cancel what’s left, exit without error (3.15+)
- Results in input order
- Exceptions as values, nothing cancelled
- Fastest first (3.13+: yields tasks)
- Wait for the first one
- Fire off a task (keep a reference!)
- Forget it when done (with a set)
- The running task
Errors in a TaskGroup
try: async with asyncio.TaskGroup() as tg: tg.create_task(ok()) tg.create_task(boom())except* ValueError as eg: for e in eg.exceptions: print("failed:", e)# one failure cancels the# other tasks in the groupPrefer TaskGroup over gather: if one task fails, the others are cancelled and the errors arrive as an ExceptionGroup.
- Cancel the block after 5 s →
TimeoutError - Set / move the deadline later
- Absolute deadline (
loop.time()clock) - Timeout for one awaitable
- The builtin, not
asyncio.TimeoutError - Request cancellation
- Clean up, then re-raise
- Protect from outer cancellation
- Was it cancelled?
Never swallow CancelledError. Catch it only to clean up, then raise; otherwise timeouts and TaskGroups stop working.
- Limit concurrency
- At most 10 at once
- Mutual exclusion
- Critical section
- One-shot signal
- Signal / wait for it
- Wait for a state change
- Wait until 3 tasks arrive
These are not thread-safe. Use them only between tasks on the same event loop.
- FIFO with back-pressure
- Waits while full
- Waits while empty
- Mark one item handled
- Wait until every item is handled
- Stop:
get()raisesQueueShutDownonce empty (3.13+) - Raises
QueueFullinstead of waiting - Smallest first (
LifoQueuetoo)
workers.py
async def worker(q): while True: url = await q.get() try: await fetch(url) finally: q.task_done()async def main(urls): q = asyncio.Queue() for u in urls: q.put_nowait(u) async with asyncio.TaskGroup() as tg: for _ in range(5): tg.create_task(worker(q)) await q.join() tg.cancel() # 3.15+- Run blocking code in a thread
- Run in a process / thread pool
- The current loop (inside async code)
- From a thread: run on the loop, wait
- From a thread: schedule a callback
- Run a callback in 5 s
Any blocking call (time.sleep, requests, heavy CPU) freezes every task. Move it to to_thread() or a process pool.
- Start a program
- Wait and collect output
- Through the shell
- Exit status (after
wait()/communicate()) - TCP client
- Read a line
- Write with back-pressure
- TCP server
- Async generator
- Consume it
- Async comprehension
- Decorator for async with
- On an
async defwith oneyield - Use it
- Many context managers at once
Command line
- REPL where top-level
awaitworks - Tasks of a running process (3.14+)
- Task tree of a running process (3.14+)
- Debug mode without code changes
In code
- Who awaits the current task (3.14+)
- Every pending task
- Name tasks for logs
- asyncio’s own logs
