Sub topic 8
Managing tasks with asyncio.TaskGroup
This chapter assumes you know async/await, can write try/except/finally, and have used asyncio.run and asyncio.create_task. It needs Python 3.11 or newer. You should also know that cancelling a task raises CancelledError inside it, which the earlier chapters on cancellation cover.
What a TaskGroup gives you
asyncio.TaskGroup is an async context manager that owns a set of tasks. It provides three guarantees:
- Every task started through the group has finished when the
async withblock exits. - If one task fails, the group cancels the others.
- Errors are never silently dropped. They are raised when the block exits.
Together these make the group a scope. No task started inside it can outlive the block. This is structured concurrency, and it fixes the two problems from the create_task and gather chapters: forgotten tasks and half-cancelled siblings.
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())tg.create_task(coro) works like asyncio.create_task. It returns a normal Task, and it also accepts name= and context= arguments. The group keeps a strong reference to each task, so you do not need a separate set to stop tasks being garbage collected.
Read results only after the block has exited. Calling t1.result() inside the block, before the task finishes, raises asyncio.InvalidStateError.
What happens when a child fails
When a task raises any exception other than CancelledError, the group does the following:
- It cancels every other unfinished child task.
- It cancels the task running the
async withbody, which interrupts whatever that body is awaiting. - It waits for all children to finish their cleanup.
- It raises an
ExceptionGroupcontaining every error that occurred.
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())slow runs its finally block because cancellation arrives as CancelledError at its await. The group always wraps errors in an ExceptionGroup, even when only one task failed. Code written as except ValueError: will not catch it. You need except*. The next chapter covers matching and splitting these groups in detail.
The body is part of the group
Step 2 above is easy to miss. The code directly inside the async with block is not exempt from cancellation.
import asyncio
async def broken():
await asyncio.sleep(0.1)
raise ValueError("child failed")
async def main():
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(broken())
try:
await asyncio.sleep(10) # the body is waiting here
finally:
print("body interrupted")
except* ValueError as eg:
print("caught:", eg.exceptions)
asyncio.run(main())The body's sleep(10) is cut short after about 0.1 seconds. The finally block runs, and the ValueError is then raised from the group.
The reverse also holds. If the body itself raises, the group cancels all children before the exception leaves the block. That exception is included in the resulting ExceptionGroup.
Starting tasks while the group is running
The async with block does not end until the group is empty. A running child can therefore add more tasks, provided it can reach the group object.
import asyncio
TREE = {"root": ["a", "b"], "a": ["a1", "a2"], "b": [], "a1": [], "a2": []}
async def visit(tg, node):
await asyncio.sleep(0.05)
print("visited", node)
for child in TREE[node]:
tg.create_task(visit(tg, child))
async def main():
async with asyncio.TaskGroup() as tg:
tg.create_task(visit(tg, "root"))
print("all nodes visited")
asyncio.run(main())This works because the group stays open while at least one task is still running. Once the group has finished, or has begun shutting down after a failure, create_task raises RuntimeError. Do not hold on to tg and call it after the block ends.
Comparing TaskGroup with gather
| Behavior | `asyncio.gather` | `asyncio.TaskGroup` |
|---|---|---|
| First task fails | Exception propagates to the caller; the other tasks keep running | Other tasks are cancelled |
| Several tasks fail | Only the first exception is raised | All are collected in an `ExceptionGroup` |
| Tasks outliving the call | Possible | Not possible |
| Getting results | A list returned by `await` | Call `.result()` on each task after the block |
| Collecting errors as values | `return_exceptions=True` | Catch inside the child (see below) |
gather is still fine for a short, flat fan-out where you want the results in a list. Prefer TaskGroup when the lifetime and cleanup of the tasks matter.
Letting tasks fail independently
Sometimes one failure should not cancel its siblings, for example when fetching many unrelated URLs. The group has no setting for this. Instead, catch the error inside the child and return it as a value.
import asyncio
async def risky(i):
await asyncio.sleep(0.05 * i)
if i == 2:
raise ValueError(f"job {i} failed")
return f"job {i} ok"
async def safe(i):
try:
return await risky(i)
except Exception as exc: # does not catch CancelledError
return exc
async def main():
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(safe(i)) for i in range(4)]
for t in tasks:
print(t.result())
asyncio.run(main())Catch Exception, not BaseException. CancelledError derives from BaseException, so cancellation still passes through. Swallowing it would break the group's ability to shut down.
Edge cases
- A child that is cancelled is not a failure. If a task ends with
CancelledError(for example because you calledtask.cancel()on it), the group treats it as finished, does not cancel the siblings, and does not add it to theExceptionGroup. - The parent being cancelled. If the task running the
async withis cancelled from outside, the group cancels all children, waits for them, and then re-raisesCancelledError. It is not wrapped in anExceptionGroup. KeyboardInterruptandSystemExit. These are not collected into the group. They propagate directly after the children are cancelled.- Errors during cleanup. A child that raises a new exception from its
finallyblock while being cancelled adds that exception to the group. The group reports it, so you never lose it. - Exception raised before any task starts. If the body raises before calling
create_task, the exception is still wrapped in anExceptionGroup.
Common mistakes
- Using
except ValueErrorinstead ofexcept* ValueErroraround a group. - Reading
.result()before the block has exited. - Using
awaitinside the body for something long-running and expecting it to finish after a sibling fails. It is cancelled. - Catching
CancelledErrorin a child and not re-raising it, which makes the group wait on a task that ignores the cancellation. - Creating a task in a group that has already exited.
Exercise
A TaskGroup contains three tasks, A, B and C. Task B raises KeyError after 0.1 seconds. Task A would take 5 seconds, and task C finishes normally after 0.05 seconds. What are the states of A and C after the async with block exits, and what is raised?
Show answer
C has already finished normally and keeps its result. A is cancelled, because the group cancels unfinished siblings when B fails, and its finally block runs first. The block raises an ExceptionGroup containing the KeyError, which you catch with except* KeyError.
Exercise
Why does safe in the independent-failure example catch Exception and not BaseException?
Show answer
CancelledError is a BaseException subclass. Catching Exception lets cancellation pass through, so the group can still cancel the task. Catching BaseException would swallow the cancellation and could leave the group waiting.