Sub topic 7
Structured concurrency with TaskGroup
This chapter assumes you can write coroutines with async def and await, start a program with asyncio.run, and create tasks with asyncio.create_task. It also assumes you know try/except and context managers.
The problem with loose tasks
create_task starts work and gives you a handle. Nothing forces you to wait for it. If you forget, the task can outlive the code that started it, and its error may surface late or never. gather helps, but if one awaitable fails, the others keep running unless you cancel them yourself.
Structured concurrency fixes this with one rule: tasks started inside a block must finish before the block ends. asyncio.TaskGroup, added in Python 3.11, enforces that rule.
Basic use
Open a group with async with. Start tasks with tg.create_task. When the block exits, the group waits for every task in it.
import asyncio
async def fetch(n):
await asyncio.sleep(0.5)
return n * 2
async def main():
async with asyncio.timeout(2):
async with asyncio.TaskGroup() as tg:
t1 = tg.create_task(fetch(1))
t2 = tg.create_task(fetch(2))
print(t1.result(), t2.result())
asyncio.run(main())The print line runs after the TaskGroup block, so both tasks are done and result() is safe to call. The outer asyncio.timeout(2) cancels the whole block if it takes longer than two seconds. Both tasks run concurrently, so this finishes in about half a second.
What happens when a task fails
If any task in the group raises an exception, the group cancels the remaining tasks and waits for them to stop. It then raises an ExceptionGroup that holds every failure. Because several tasks may fail, you handle the result with except*, not except.
import asyncio
async def ok():
return 1
async def bad():
raise ValueError("boom")
async def main():
results = await asyncio.gather(ok(), bad(), return_exceptions=True)
print(results)
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(ok())
tg.create_task(bad())
except* ValueError as eg:
print("caught", len(eg.exceptions), "ValueError")
asyncio.run(main())The first half shows gather with return_exceptions=True. The exception comes back as a value in the list, and the other results are kept. The second half shows the group. except* ValueError matches the ValueError entries inside the group, and eg is a smaller ExceptionGroup containing only those.
gather versus TaskGroup
| Question | `gather` | `TaskGroup` |
|---|---|---|
| First failure | Raised to the caller, other tasks keep running | Other tasks are cancelled |
| Several failures | Only the first is raised, unless `return_exceptions=True` | All collected in an `ExceptionGroup` |
| Results | A list in input order | Read from each task with `result()` |
| Python version | All 3.x | 3.11 and later |
Use gather when you want a list of results and partial failure is acceptable. Use TaskGroup when the tasks form one unit of work and a failure should stop the rest.
Common mistakes
- Reading
t1.result()inside theasync withblock. The task may not be finished yet. - Catching with plain
except ValueError. AnExceptionGroupdoes not match it, so the error passes through. - Swallowing
CancelledErrorinside a task. The group relies on cancellation to stop siblings.
Exercise
A TaskGroup contains three tasks. Task A raises KeyError after 0.1 seconds. Tasks B and C each sleep for 5 seconds. What happens, and which except form catches the error?
Show answer
When A fails, the group cancels B and C, waits for them to stop, and raises an ExceptionGroup containing the KeyError. The block ends after about 0.1 seconds, not 5. Catch it with except* KeyError, because plain except KeyError does not match an ExceptionGroup.