Sub topic 1
Python asyncio Task Groups, Timeouts, and Cancellation
Prerequisites
This chapter assumes Python 3.11 or newer, async/await, try/except/finally, context managers, and basic use of asyncio.run().
Coroutines, tasks, and the event loop in brief
A coroutine is an async function that can pause at an await. The event loop runs coroutines and switches to other ready work while one coroutine is waiting. This creates concurrency without requiring a separate thread for every operation.
A task is a scheduled coroutine. It lets the event loop run that coroutine independently while the current coroutine continues.
import asyncio
async def main():
await asyncio.sleep(0.1)
print("finished")
asyncio.run(main())Running work concurrently with `create_task`
Use asyncio.create_task() when work should start before you await its result. The returned Task object is a handle for checking or awaiting that work.
import asyncio
async def fetch(name, delay):
await asyncio.sleep(delay)
return f"{name} done"
async def main():
first = asyncio.create_task(fetch("first", 0.2))
second = asyncio.create_task(fetch("second", 0.1))
print(await first)
print(await second)
asyncio.run(main())Both operations start before either result is awaited. The event loop alternates between them during their waits.
Fire-and-forget tasks and references
A fire-and-forget task continues after the creating coroutine stops awaiting it. Keep a strong reference to such tasks. Otherwise, a task can be garbage-collected before it finishes. A set is useful for tracking several background tasks.
background = set()
task = asyncio.create_task(fetch("audit", 1))
background.add(task)
task.add_done_callback(background.discard)This pattern also gives shutdown code a collection of tasks to await.
> Note > Prefer a TaskGroup for related work. It gives tasks a scope and makes failures and cleanup easier to reason about.
`asyncio.gather` and where it falls short
asyncio.gather() waits for several awaitables and returns results in input order, even if they finish in another order. By default, the first raised exception is propagated, but other awaitables may continue running. That behavior can leave related work alive after the caller sees an error. TaskGroup is usually safer when sibling tasks should share one lifetime.
How task cancellation works
Calling task.cancel() requests cancellation. At the task’s next suspension point, Python raises asyncio.CancelledError inside that task. Cleanup belongs in finally, and cancellation should normally be re-raised after cleanup.
async def worker():
try:
await asyncio.sleep(10)
finally:
print("resources released")Exercise
What happens if worker_task.cancel() is called while worker() is sleeping?
Show answer
CancelledError is raised at the sleep point, the finally block runs, and the error reaches the code awaiting the task.