Sub topic 6
Collecting results with asyncio.gather
This chapter assumes you can write coroutines with async def and await, start them with asyncio.run, and wrap them in tasks with asyncio.create_task. It also assumes you know basic try/except.
What gather does
asyncio.gather takes several awaitables and runs them concurrently. It returns one list with their results, in the same order you passed them. Coroutines that are not yet tasks get wrapped in tasks for you. You await the call once, and you get everything back together.
The example below runs three one-second coroutines at once.
import asyncio
import time
async def fetch(n):
await asyncio.sleep(1)
return n * 2
async def main():
start = time.perf_counter()
results = await asyncio.gather(fetch(1), fetch(2), fetch(3))
elapsed = time.perf_counter() - start
print(results, f"{elapsed:.1f}s")
asyncio.run(main())The program prints [2, 4, 6] 1.0s. Each coroutine suspends at await asyncio.sleep(1), so the event loop starts all three before any finishes. Awaiting them one after another would take about three seconds.
Result order
The result list follows argument order, not completion order. If fetch(3) finishes first, its result is still last. This lets you unpack results safely:
a, b, c = await asyncio.gather(fetch(1), fetch(2), fetch(3))To gather a dynamic number of awaitables, unpack a generator or list with *:
results = await asyncio.gather(*(fetch(n) for n in range(10)))Note that gather does not limit concurrency. All ten start at once. Use a semaphore if you need a cap, which a later chapter covers.
When one awaitable fails
By default, the first exception raised by any awaitable propagates out of await asyncio.gather(...). The other awaitables are not cancelled. They keep running, but you no longer receive their results. This is a common source of surprises.
Pass return_exceptions=True to change this. Exceptions then appear as values in the result list, and you inspect each entry yourself.
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)
asyncio.run(main())This prints [1, ValueError('boom')]. Check each entry with isinstance(r, Exception) before using it.
gather or TaskGroup
| Question | gather | TaskGroup |
|---|---|---|
| Results | One list, in input order | You read each task's `result()` |
| First failure | Propagates, siblings keep running | Cancels siblings, raises an `ExceptionGroup` |
| Python version | All asyncio versions | 3.11 and later |
| Best for | Quick fan-out where you want a list | Work that must not leak running tasks |
Use gather when you want a simple ordered list and can tolerate partial failure with return_exceptions=True. Prefer TaskGroup, covered in the next chapter, when a failure should stop the rest of the work.
Common mistakes
- Passing
fetch(1)results instead of coroutines, such asgather(await fetch(1)). This runs the call sequentially and passes a plain value, whichgatherrejects. - Forgetting to
awaitthegathercall. You then get a future, not a list. - Assuming a failure cancels the other awaitables.
Exercise
You call await asyncio.gather(a(), b(), c()). Coroutine b raises KeyError after 0.1 seconds, while a and c take 5 seconds. What reaches your code at 0.1 seconds, and what happens to a and c?
Show answer
The KeyError propagates out of the await at once, and you receive no result list. a and c are not cancelled. They keep running in the background, and their results are lost to this call. Adding return_exceptions=True would make gather wait for all three and return the KeyError as a list entry.
Exercise
How would you run fetch(n) for n from 0 to 4 concurrently and get the results in order?
Show answer
results = await asyncio.gather(*(fetch(n) for n in range(5))). The results come back in argument order, so results[i] belongs to fetch(i).