Sub topic 12
Putting a timeout around a task group
This chapter assumes you know asyncio.TaskGroup, asyncio.timeout, and how CancelledError works. You need Python 3.11 or newer.
Why combine them
A task group waits for all of its tasks. If one task hangs, the group hangs too. A deadline around the group sets an upper limit on the whole batch of work.
Timeout outside the group
Put asyncio.timeout on the outside and the TaskGroup on the inside.
import asyncio
async def work(i):
await asyncio.sleep(i)
print(f"work {i} finished")
async def main():
try:
async with asyncio.timeout(1.5):
async with asyncio.TaskGroup() as tg:
for i in range(1, 4):
tg.create_task(work(i))
except TimeoutError:
print("deadline hit, remaining tasks were cancelled")
asyncio.run(main())Here work 1 finishes at 1 second and prints its message. At 1.5 seconds the deadline passes, and the following steps happen:
- The timeout cancels the task running
main, which is waiting at the end of theTaskGroupblock. - The group cancels its unfinished children,
work 2andwork 3, and waits for them to stop. - The
CancelledErrorleaves the group, andtimeoutturns it into aTimeoutError.
The children's cleanup finishes before your except TimeoutError handler runs. When the handler starts, no task from that group is still running.
Timeout inside the group
Moving the timeout inside gives a different result. A timeout wrapped around one child's work affects only that child.
import asyncio
async def limited(i):
async with asyncio.timeout(1):
await asyncio.sleep(i)
print(f"limited {i} finished")
async def main():
try:
async with asyncio.TaskGroup() as tg:
for i in (0.5, 3):
tg.create_task(limited(i))
except* TimeoutError as eg:
print("timed out:", len(eg.exceptions))
asyncio.run(main())The child that sleeps 3 seconds raises TimeoutError after 1 second. For the group, that is an ordinary child failure. The group cancels the other children and raises an ExceptionGroup, so you must catch it with except*.
Choosing the placement
| Placement | What expires | What you catch |
|---|---|---|
| Outside the group | The whole batch | `TimeoutError` |
| Inside one child | That child's operation | `TimeoutError` inside an `ExceptionGroup` (`except*`) |
Use the outer form when the caller cares about total time. Use the inner form when each operation has its own budget.
Common mistakes
- Catching
TimeoutErrorwith plainexceptaround a timeout placed inside a child. The error arrives wrapped in anExceptionGroup, so the handler never matches. - Placing
except TimeoutErrorinside theasync with asyncio.timeout(...)block. The error is raised only after the block exits, so the handler must be outside it. - Expecting the timeout to fire during blocking code. Cancellation is delivered only at an
await, so a long synchronous call delays the deadline.
Exercise
In the first example, work 1 finishes at 1 second and the timeout is 1.5 seconds. Which messages print, and why does the "deadline hit" message appear after the children have stopped?
Show answer
Only "work 1 finished" and then "deadline hit, remaining tasks were cancelled" print. work 2 and work 3 are cancelled at 1.5 seconds before they finish. The TaskGroup waits for its cancelled children to finish unwinding before it exits, and only then does timeout convert the cancellation into TimeoutError, so the handler runs after the children have stopped.