Sub topic 7
Structured concurrency: tasks that cannot outlive their scope
This chapter assumes you know async/await, asyncio.create_task, and try/finally. It also assumes you have read the previous chapters on gather and on handling CancelledError. You need Python 3.11 or newer.
The problem: tasks that outlive their caller
A task made with create_task runs on its own. Nothing ties its lifetime to the function that started it. That function can return, raise, or be cancelled while the task keeps running, and the task's own errors may never reach anyone.
asyncio.gather only partly fixes this. When one awaitable raises, gather re-raises the error at once, but it does not cancel the others.
import asyncio
async def ok():
await asyncio.sleep(0.3)
print("ok: finished")
async def bad():
await asyncio.sleep(0.1)
raise ValueError("boom")
async def main():
try:
await asyncio.gather(ok(), bad())
except ValueError:
print("gather raised, but ok() is still running")
await asyncio.sleep(0.5)
asyncio.run(main())The except block runs at 0.1 seconds. At 0.3 seconds ok() prints "ok: finished" anyway. Without the final sleep, asyncio.run would cancel it during shutdown and you would never see that line. The caller believed the work had failed and ended, yet part of it was still alive.
The idea
Structured concurrency is a rule: every task started inside a block must finish before the block exits. This is the same rule that makes a function call safe. When a call returns, nothing that call started is still running.
That rule gives you three guarantees:
- No orphans. Leaving the block means all child tasks are done.
- No lost errors. A child's failure is raised in the code that owns the block.
- Cancellation flows downward. If the block is cancelled, or one child fails, the other children are cancelled too.
The same example in a scope
asyncio.TaskGroup is the standard library's structured scope. The next chapter covers its API in detail. Here it only shows the guarantee.
import asyncio
async def ok():
await asyncio.sleep(0.3)
print("ok: finished")
async def bad():
await asyncio.sleep(0.1)
raise ValueError("boom")
async def main():
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(ok())
tg.create_task(bad())
except* ValueError:
print("group raised, and ok() was cancelled first")
await asyncio.sleep(0.5)
asyncio.run(main())When bad() fails, the group cancels ok() and waits for it to stop. Only then does the async with block raise. "ok: finished" never prints, even with the final sleep. By the time the except* clause runs, no child is left.
Why cleanup code matters here
The group stops siblings by cancelling them. Each sibling gets CancelledError at its next await. Your finally blocks run, and you should re-raise CancelledError, as covered in the previous chapter. If a child swallows it, the scope cannot finish its promise to end quickly.
Common mistakes
- Calling
create_taskinside a group-managed function but storing the task somewhere that outlives the group. The group only owns tasks created throughtg.create_task. - Assuming
gather(..., return_exceptions=True)is structured. It collects errors, but it still does not cancel siblings. - Reading
task.result()inside the block before the tasks finish. Read results after theasync withexits.
Exercise
In the gather example, why does "ok: finished" print even though main saw a ValueError? What changes with a TaskGroup?
Show answer
gather re-raises the first error but does not cancel the other awaitables, so ok() keeps running to completion. A TaskGroup cancels the remaining children when one fails and waits for them to stop before raising, so ok() never reaches its print.