Sub topic 8
Managing tasks with asyncio.TaskGroup
This chapter assumes you know Python 3.11 or newer, async/await, try/finally, and async with. It also assumes you know how asyncio.create_task and asyncio.run work.
The problem it solves
asyncio.create_task starts a task, but nothing forces you to wait for it. A task can outlive the function that created it, and its error can go unnoticed. asyncio.TaskGroup fixes this by tying the lifetime of its tasks to an async with block.
The basic pattern
import asyncio
async def fetch(name, delay):
await asyncio.sleep(delay)
return f"{name} done"
async def main():
async with asyncio.TaskGroup() as tg:
t1 = tg.create_task(fetch("a", 0.2))
t2 = tg.create_task(fetch("b", 0.1))
# The async with block exits only after both tasks finish.
print(t1.result(), t2.result())
asyncio.run(main())Three points about this code:
tg.create_task(...)takes a coroutine and returns a normalasyncio.Task.- The group keeps its own reference to each task, so you do not need to store them to keep them alive.
- Leaving the block waits for every task. Calling
result()afterwards is safe because all tasks are finished.
What happens when a task fails
If any task in the group raises an exception other than CancelledError, the group does three things:
- It cancels all sibling tasks that are still running.
- It waits for those tasks to finish their cleanup.
- It raises an
ExceptionGroupthat contains the failures.
import asyncio
async def slow():
try:
await asyncio.sleep(10)
finally:
print("slow: cleaned up")
async def broken():
await asyncio.sleep(0.1)
raise ValueError("something went wrong")
async def main():
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(slow())
tg.create_task(broken())
except* ValueError as eg:
print("caught:", eg.exceptions)
asyncio.run(main())broken fails after 0.1 seconds. The group cancels slow, whose finally block prints its message. Then except* catches the ValueError. The next chapter covers ExceptionGroup and except* in detail. For now, remember that a TaskGroup always raises an ExceptionGroup, even when only one task failed.
Behaviors to remember
- Errors in the body count too. If code inside the
async withblock raises, the group cancels its children and then raises. - Results are not collected for you. Keep the task objects, as
t1andt2above, and readresult()after the block. - Cancelled siblings are not errors. A task cancelled by the group does not add a
CancelledErrorto theExceptionGroup. - Add tasks only while the group is active. Calling
create_taskafter the block has exited raisesRuntimeError.
Compared with gather
With gather, a failing task does not cancel the others by default. They keep running, possibly unobserved. A TaskGroup gives you the all-or-nothing behavior most programs actually want.
Exercise
In a TaskGroup, task A raises RuntimeError after 1 second. Task B is in await asyncio.sleep(60). What happens to B, and what does the code after the async with block see?
Show answer
The group cancels B, so B receives CancelledError at its await and runs any finally cleanup. The group waits for B to finish, then raises an ExceptionGroup containing the RuntimeError. Code after the block does not run unless you handle the group with except*.