Sub topic 4
asyncio.gather and where it falls short
This chapter assumes you know async/await, can start a program with asyncio.run, and have seen asyncio.create_task. You will see how asyncio.gather runs awaitables together and why it can leave work running after a failure.
What gather does
asyncio.gather(*aws) runs several awaitables concurrently. It wraps any bare coroutine in a task, waits for all of them, and returns their results in the order you passed them in, not the order they finished.
import asyncio
async def fetch(name, delay):
await asyncio.sleep(delay)
return f"{name} done"
async def main():
results = await asyncio.gather(fetch("a", 0.2), fetch("b", 0.1))
print(results) # ['a done', 'b done']
asyncio.run(main())For simple fan-out where every call succeeds, this is short and readable.
Failure behavior
By default, the first exception raised by any child is re-raised from await gather(...). The other children are not cancelled. They keep running, and nothing in your code owns them anymore.
import asyncio
async def slow():
await asyncio.sleep(0.3)
print("slow: finished anyway")
async def broken():
await asyncio.sleep(0.1)
raise ValueError("boom")
async def main():
try:
await asyncio.gather(slow(), broken())
except ValueError as e:
print("gather raised:", e)
await asyncio.sleep(0.5) # keep the loop alive so slow can finish
asyncio.run(main())The output shows gather raised: boom first, and slow: finished anyway afterwards. Without the final sleep, asyncio.run would cancel slow while shutting down. The error handler ran while a sibling task was still active.
return_exceptions=True
With return_exceptions=True, gather waits for every child. Exceptions are placed in the result list instead of being raised.
import asyncio
async def ok():
return "ok"
async def bad():
raise ValueError("boom")
async def main():
results = await asyncio.gather(ok(), bad(), return_exceptions=True)
for r in results:
if isinstance(r, Exception):
print("failed:", r)
else:
print("success:", r)
asyncio.run(main())This fixes the "sibling keeps running" problem, but it moves the burden to you. Forgetting the isinstance check silently treats an exception object as data. Nothing stops the other tasks early when one fails.
Where gather falls short
- No cancellation of siblings. One failure does not stop the rest, so they can waste time or hold resources.
- Only one error is raised. In default mode you see the first exception. Later ones are not reported to you.
- Weak scoping. After an exception, children can outlive the code that started them.
- Cancellation goes one way. If the task awaiting
gatheris cancelled, the children are cancelled too. A failing child does not cancel the others.
| Behavior | `gather` (default) | `gather(return_exceptions=True)` | `TaskGroup` |
|---|---|---|---|
| Child fails | First error raised, siblings keep running | Error stored in results | Siblings cancelled, errors raised together |
| Multiple errors | Only the first is raised | All stored in results | All collected in an `ExceptionGroup` |
| Tasks outlive the block | Possible | No | Not possible |
When gather is still fine
Use gather for short, independent calls where you want every outcome, usually with return_exceptions=True. Use a TaskGroup when the tasks form one unit of work and a failure should stop the rest. The next chapters cover cancellation and then TaskGroup.
Exercise
In await asyncio.gather(a(), b()), task a raises an exception while b is still sleeping. What happens to b, and which option makes the exception appear in the results list instead of being raised?
Show answer
b is not cancelled and keeps running, while the exception from a is re-raised to the caller of await gather(...). Passing return_exceptions=True puts the exception in the results list and makes gather wait for all children.