Sub topic 7
Structured concurrency with TaskGroup
This chapter assumes you can already write coroutines, start tasks with asyncio.create_task, and use asyncio.gather. You should also know try/except and context managers. TaskGroup needs Python 3.11 or later, and the except* syntax shown below does too.
The problem with loose tasks
asyncio.create_task starts a task and returns immediately. Nothing forces you to wait for it. If you forget to await the task, it can keep running after the function that created it has returned. If it fails, the error may surface only as a "Task exception was never retrieved" message at garbage-collection time.
asyncio.gather improves on this, but it has gaps:
- If one awaitable raises,
gatherpropagates that exception to the caller. The other awaitables keep running in the background. - With
return_exceptions=True, every failure becomes a value in the result list, and you must remember to inspect each one. - If you cancel the task that called
gather, the cancellation propagates to the children, but nothing ties the children's lifetime to a block of code.
Structured concurrency fixes this with one rule: child tasks live inside a block of code, and the block cannot finish until every child is finished. asyncio.TaskGroup implements that rule.
The basic pattern
import asyncio
async def fetch(n):
await asyncio.sleep(0.5)
return n * 2
async def main():
async with asyncio.TaskGroup() as tg:
t1 = tg.create_task(fetch(1))
t2 = tg.create_task(fetch(2))
t3 = tg.create_task(fetch(3))
# Every task is finished here.
print([t.result() for t in (t1, t2, t3)])
asyncio.run(main())This prints [2, 4, 6] after about half a second. Three things to notice:
- You create tasks with
tg.create_task(...), notasyncio.create_task(...). The group registers each task as one of its children. - Leaving the
async withblock awaits every child. The code after the block runs only when all of them are done. - Results come from the
Taskobjects. Unlikegather, the group does not return a list, so keep the task references you need.
Tasks start running when the body of the block next yields to the event loop, not at the moment you call tg.create_task. The implicit wait at the end of the block is one such yield.
What happens when a child fails
The group's failure rules are the main reason to use it:
- A child raises an exception other than
CancelledError. - The group cancels all its other children.
- If the body of the
async withblock is still running, the group cancels that too. The body receivesCancelledErrorat its currentawait. - The group waits for every child to finish, including the cancelled ones.
- The group raises an
ExceptionGroupthat holds every exception collected.
import asyncio
async def worker(name, delay, fail=False):
try:
await asyncio.sleep(delay)
if fail:
raise ValueError(f"{name} failed")
print(name, "finished")
return name
except asyncio.CancelledError:
print(name, "cancelled")
raise
async def main():
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(worker("a", 0.1, fail=True))
tg.create_task(worker("b", 1))
tg.create_task(worker("c", 1))
except* ValueError as eg:
print("caught:", [str(e) for e in eg.exceptions])
asyncio.run(main())Task a fails after 0.1 seconds. The group cancels b and c, so you see b cancelled and c cancelled. Then the except* clause prints caught: ['a failed']. Nothing is left running when execution continues after the block.
ExceptionGroup and except*
A TaskGroup always raises an ExceptionGroup, even when only one task failed. Writing except ValueError: around the block therefore does not match. Use except*, which matches the exceptions of a given type inside the group:
import asyncio
async def bad_value():
raise ValueError("bad value")
async def bad_key():
raise KeyError("missing")
async def main():
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(bad_value())
tg.create_task(bad_key())
except* ValueError as eg:
print("values:", [str(e) for e in eg.exceptions])
except* KeyError as eg:
print("keys:", len(eg.exceptions))
asyncio.run(main())Each except* clause receives a new group containing only the matching exceptions, and eg.exceptions is a tuple of them. More than one except* clause can run for the same raised group. Exceptions that no clause matches are re-raised in a group afterwards.
Both tasks above fail at their first step, so both exceptions are collected. If a task had been cancelled by the group before it could fail, its CancelledError would not appear in the group. The group never reports cancellations it caused itself.
Two other rules are worth knowing:
KeyboardInterruptandSystemExitraised by a child are not wrapped. They propagate directly.- If the block body itself raises, the group cancels all children and includes that exception in the
ExceptionGroup.
Comparing gather and TaskGroup
| Aspect | `asyncio.gather` | `asyncio.TaskGroup` |
|---|---|---|
| Accepts | Coroutines, tasks, futures | Coroutines, passed to `tg.create_task` |
| Results | Ordered list returned by `await` | Read from each `Task` object |
| First failure | Propagates it, siblings keep running | Cancels siblings and the block body |
| Multiple failures | Only the first is raised, unless `return_exceptions=True` | All collected into an `ExceptionGroup` |
| Add tasks dynamically | No | Yes, while the block is open |
| Python version | All asyncio versions | 3.11+ |
Choose gather for a short, fixed set of independent operations when you want a result list or want errors as values. Choose TaskGroup when failure of one task should stop the rest, or when the set of tasks is not known up front.
Adding tasks while the group runs
Because the group is a block, tasks can create more tasks on the same group. A crawler that follows links is the typical case:
import asyncio
async def visit(tg, depth, seen):
print("visiting depth", depth)
await asyncio.sleep(0.1)
if depth < 2:
for child in range(2):
key = (depth, child, len(seen))
seen.add(key)
tg.create_task(visit(tg, depth + 1, seen))
async def main():
seen = set()
async with asyncio.TaskGroup() as tg:
tg.create_task(visit(tg, 0, seen))
print("tasks started:", len(seen) + 1)
asyncio.run(main())The block waits until all tasks, including ones added while it waits, are done. Once the group has finished, calling create_task on it raises RuntimeError. A group is single-use.
Letting siblings survive
Sometimes one failure should not stop the others, for example when you download ten files and want the nine that succeed. Catch the exception inside the child, so the group never sees it:
import asyncio
async def safe(coro):
try:
return await coro
except Exception as exc:
return exc
async def job(n):
await asyncio.sleep(0.1)
if n == 2:
raise RuntimeError(f"job {n} failed")
return n
async def main():
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(safe(job(n))) for n in range(4)]
for t in tasks:
print(t.result())
asyncio.run(main())The group completes normally, and each result() is either a value or an exception object. Catch Exception, not BaseException, so cancellation still propagates.
Combining with timeouts
A group is a natural unit to put a deadline on. Wrap the group in asyncio.timeout, as in this chapter's earlier pattern:
import asyncio
async def slow():
await asyncio.sleep(5)
async def main():
try:
async with asyncio.timeout(1):
async with asyncio.TaskGroup() as tg:
tg.create_task(slow())
tg.create_task(slow())
except TimeoutError:
print("gave up after 1 second")
asyncio.run(main())When the timeout fires, it cancels the task running main. The group treats that as a cancellation of its body, cancels both children, waits for them, and lets CancelledError pass up to asyncio.timeout, which converts it to TimeoutError. Because the timeout wraps the group from outside, you catch a plain TimeoutError, not an exception group.
Pitfalls
Other common mistakes:
- Writing
except ValueError:instead ofexcept* ValueError:around the block, so the handler never runs. - Calling
asyncio.create_taskinside the block instead oftg.create_task. The task is not attached to the group, so its failures and lifetime are not managed. - Reading
t.result()inside the block before the task has finished, which raisesInvalidStateError. Read results after the block exits. - Using
await tg.create_task(...).create_taskreturns aTaskimmediately. You do not need to await it at creation time, and doing so makes the work sequential.
Exercise
A TaskGroup contains three tasks: A raises ValueError after 0.1 seconds, B sleeps for 1 second, and C raises KeyError after 0.2 seconds. The caller wraps the block in except* ValueError. What does B do, and what does the caller observe?
Show answer
When A fails at 0.1 seconds, the group cancels B and C. C never reaches its 0.2-second failure, so the KeyError is never raised. B receives CancelledError and ends as cancelled. The group then raises an ExceptionGroup containing only A's ValueError, and the except* ValueError clause handles it. If C had failed before A's failure triggered cancellation, the KeyError would also be in the group, and the except* ValueError clause alone would leave it unhandled, re-raising it in a group.
Exercise
You need to fetch 20 URLs and keep every successful response, even if some requests fail. Would you use a bare TaskGroup with tg.create_task(fetch(url))? If not, what would you change?
Show answer
No. With a bare TaskGroup, the first failure cancels the remaining fetches and the successful results are lost behind the ExceptionGroup. Wrap each fetch in a helper that catches Exception and returns it as a value (or use gather(..., return_exceptions=True)), so the group never sees the failures. Then check each task's result after the block exits.