Sub topic 4
asyncio.gather and where it falls short
This chapter assumes you know async/await, asyncio.run, and asyncio.create_task. It also assumes you understand try/finally and Python 3.11 or newer. asyncio.gather is the most common way to run several awaitables at once, and many codebases use it by default. It works well when everything succeeds. Its failure behavior is the reason asyncio.TaskGroup exists, so this chapter looks at that behavior closely.
What gather does
asyncio.gather(*aws) takes coroutines, tasks, or futures and schedules them to run concurrently. Any bare coroutine is wrapped in a task for you. It returns a single awaitable that completes when all children are done. The result is a list in the same order as the arguments, not in completion order.
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)
asyncio.run(main())This prints ['a done', 'b done']. Task b finishes first, but its result is still second in the list. The whole call takes about 0.2 seconds rather than 0.3.
Default failure behavior: siblings keep running
With the default return_exceptions=False, the first exception raised by any child is re-raised from await gather(...). The other children are not cancelled. They keep running in the background, and nothing is left to wait for them.
import asyncio
async def slow():
try:
await asyncio.sleep(0.5)
print("slow: finished anyway")
finally:
print("slow: exiting")
async def broken():
await asyncio.sleep(0.1)
raise ValueError("boom")
async def main():
try:
await asyncio.gather(slow(), broken())
except ValueError as exc:
print("gather raised:", exc)
print("main continues")
await asyncio.sleep(1)
print("main done")
asyncio.run(main())The output is:
gather raised: boom
main continues
slow: finished anyway
slow: exiting
main doneThe except block ran while slow was still in progress. Your code believes the operation failed and moves on, but one of its pieces is still using the network, a file, or a database connection. If main returned right after the except block, asyncio.run would cancel slow during shutdown. That cancellation would happen at an arbitrary time and for a reason unrelated to your logic.
Only one exception is reported
If several children fail, gather raises only the first exception. The others are not reported to you and are not attached to the one you receive. You cannot tell afterwards how many things went wrong. A TaskGroup collects them all in an ExceptionGroup, which a later chapter covers.
return_exceptions=True moves the problem
Passing return_exceptions=True makes gather wait for every child. Exceptions appear in the result list instead of being raised.
import asyncio
async def ok():
return 1
async def bad():
raise RuntimeError("bad")
async def main():
results = await asyncio.gather(ok(), bad(), ok(), return_exceptions=True)
for item in results:
if isinstance(item, BaseException):
print("failed:", repr(item))
else:
print("ok:", item)
asyncio.run(main())You now see every outcome, but three costs remain:
- Nothing raises by default. If you forget the
isinstancecheck, errors pass silently as ordinary values. - A failure does not stop its siblings. If
bad()fails in the first millisecond, the other children still run to completion. - A child that was cancelled shows up in the list as a
CancelledErrorinstance, mixed in with ordinary results.
Use this mode when you really want every result, as in "check ten servers and report on each". Don't use it as a way to silence errors.
Cancelling gather cancels its children
Cancellation works differently in the other direction. If the gather future itself is cancelled, it cancels every child. Cancelling the task that is awaiting it has the same effect.
import asyncio
async def worker(n):
try:
await asyncio.sleep(10)
finally:
print(f"worker {n} cleaned up")
async def main():
group = asyncio.gather(worker(1), worker(2))
await asyncio.sleep(0.1)
group.cancel()
try:
await group
except asyncio.CancelledError:
print("gather cancelled")
asyncio.run(main())Both workers run their finally blocks before gather cancelled prints. This is also why asyncio.wait_for(asyncio.gather(...), timeout) stops the children when the deadline passes. So a deadline cancels the whole batch, but an error in one child does not. A failure and a timeout leave the siblings in different states.
A confusing child cancellation
When a child is cancelled on its own, for example because some other code holds a reference and calls cancel() on it, gather does not raise a distinct error. With return_exceptions=False, the await raises CancelledError. From the caller's side this looks the same as the caller itself being cancelled. Code that catches CancelledError to mean "I was told to stop" may then react wrongly to a cancellation that happened somewhere else. The same ambiguity shows up in later chapters, and it is one reason cancellation handling needs care.
Cancelling siblings by hand
You can build the "cancel the others on first failure" behavior yourself. It takes surprisingly many lines to get right:
import asyncio
async def run_all(coros):
tasks = [asyncio.create_task(c) for c in coros]
try:
return await asyncio.gather(*tasks)
except BaseException:
for t in tasks:
t.cancel()
# Wait so cancelled tasks finish their cleanup before we leave.
await asyncio.gather(*tasks, return_exceptions=True)
raise
async def ok():
await asyncio.sleep(0.2)
return "ok"
async def broken():
await asyncio.sleep(0.05)
raise ValueError("boom")
async def main():
try:
await run_all([ok(), broken()])
except ValueError as exc:
print("raised:", exc)
asyncio.run(main())Several details matter here:
- You must create the tasks yourself so you hold references to them.
- The
exceptclause cancels every task, including ones that are already done. That is harmless, becausecancel()on a finished task does nothing. - The second
gatherwithreturn_exceptions=Truewaits for cleanup. Without it, the cancelled tasks may still be unwinding when you continue. - It catches
BaseException, so it also handles the case where the caller is cancelled. - It still loses secondary exceptions.
Most hand-written versions skip steps 3 or 4. TaskGroup does all of this for you.
Other limits
- Dynamic work.
gathertakes a fixed set of awaitables up front. You cannot add a task to a runninggather. ATaskGrouplets you callcreate_taskon it as new work appears. - No concurrency limit.
gather(*[fetch(u) for u in urls])starts every coroutine at once. With ten thousand URLs this can exhaust sockets or overload a server. Limiting concurrency needs a semaphore, covered in a later chapter. - No scope. The
gathercall returns after an error while children continue. Nothing in the language guarantees that a task ends before the function that started it. The next chapters call this property structured concurrency.
gather compared with TaskGroup
| Situation | `asyncio.gather` | `asyncio.TaskGroup` |
|---|---|---|
| One child raises | Error re-raised; siblings keep running | Siblings cancelled and awaited, then error raised |
| Several children raise | Only the first is raised | All raised together in an `ExceptionGroup` |
| Result order | List in argument order | Read each task's `.result()` |
| Add tasks while running | Not possible | `create_task` any time before the block ends |
| Outer cancellation | Cancels children | Cancels children, waits for them |
gather is still reasonable for a small, fixed set of independent calls where you want an ordered list back and a failure would end the program anyway. For anything that holds resources or needs reliable cleanup, prefer a TaskGroup.
Exercise
A coroutine calls await asyncio.gather(a(), b()). Task b raises KeyError after 0.1 seconds, while a needs 2 seconds and has a finally block that closes a connection. The caller catches KeyError and returns immediately. Is the connection closed at 0.1 seconds? What changes if you pass return_exceptions=True?
Show answer
No. gather does not cancel a when b fails, so a keeps running and its finally block only runs when a ends. That happens at about 2 seconds if the event loop is still running then, or earlier if asyncio.run cancels it during shutdown. With return_exceptions=True, nothing is raised at 0.1 seconds. gather waits until a finishes at 2 seconds, and the KeyError appears as an item in the result list.
Exercise
You run await asyncio.gather(f(), g()) and both f and g raise different exceptions. How many of them does your try/except see, and how could you see both?
Show answer
It sees only the first exception to be raised. The other is dropped. To see both, use return_exceptions=True and inspect the result list, or use a TaskGroup, which raises an ExceptionGroup containing both.