Sub topic 6
Collecting results with asyncio.gather
This chapter assumes you can write coroutines with async def and await, start a program with asyncio.run, and wrap a coroutine in a task with asyncio.create_task. It also assumes you know how try/except behaves. asyncio.gather is the shortest way to run several awaitables at once and get their results back as one list.
What gather does
asyncio.gather(*aws) takes any number of awaitables. It wraps each bare coroutine in a task, so they all start running on the event loop, and returns a single awaitable. When you await it, you get a list of results once every child has finished.
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())This prints [2, 4, 6] 1.0s. Awaiting the three calls one after another would take about three seconds, because each await would finish before the next coroutine started. With gather, all three sleep at the same time.
Result order follows the arguments
The list gather returns is in the same order as the arguments. It is not in the order the tasks finished. You can pair results with inputs by position without extra bookkeeping.
import asyncio
async def job(name, delay):
await asyncio.sleep(delay)
print("finished", name)
return name
async def main():
results = await asyncio.gather(
job("slow", 0.3),
job("fast", 0.1),
job("medium", 0.2),
)
print(results)
asyncio.run(main())The output is:
finished fast
finished medium
finished slow
['slow', 'fast', 'medium']The completion messages arrive in time order. The returned list stays in argument order. If you need results as they complete, use asyncio.as_completed or a queue instead.
Gathering a dynamic number of awaitables
gather takes positional arguments, not a list. To run a variable number of coroutines, unpack a generator or list with *.
import asyncio
async def square(n):
await asyncio.sleep(0.1)
return n * n
async def main():
numbers = [1, 2, 3, 4, 5]
results = await asyncio.gather(*(square(n) for n in numbers))
print(dict(zip(numbers, results)))
asyncio.run(main())Gathering nothing is legal. await asyncio.gather() returns [] immediately, so an empty input list needs no special case.
Starting thousands of coroutines this way creates thousands of tasks at once. Cap the concurrency with a semaphore, which a later chapter covers.
Errors with the default setting
By default, the first exception raised by any child is propagated straight to the code awaiting gather. The important detail is what happens to the other children. They are not cancelled. They keep running, and their results are lost.
import asyncio
async def bad():
await asyncio.sleep(0.1)
raise ValueError("boom")
async def slow():
await asyncio.sleep(0.5)
print("slow finished")
return "slow"
async def main():
try:
await asyncio.gather(bad(), slow())
except ValueError as exc:
print("caught", exc)
await asyncio.sleep(1)
asyncio.run(main())The program prints caught boom after 0.1 seconds. Then, at 0.5 seconds, it prints slow finished. The slow task still ran to completion, but nobody received its return value. If the children hold resources or have side effects, this can surprise you.
Only the first exception reaches you. If two children fail, the second exception is not raised. Python does not log it as a "never retrieved" error either, because gather has already consumed it.
Collecting errors with return_exceptions
Passing return_exceptions=True changes the contract. gather always waits for every child. An exception is placed in the result list at that child's position, as a value, instead of being raised.
import asyncio
async def fetch(n):
await asyncio.sleep(0.1)
if n % 2:
raise ValueError(f"bad input {n}")
return n * 10
async def main():
inputs = [0, 1, 2, 3]
results = await asyncio.gather(
*(fetch(n) for n in inputs), return_exceptions=True
)
for n, result in zip(inputs, results):
if isinstance(result, BaseException):
print(n, "failed:", result)
else:
print(n, "ok:", result)
asyncio.run(main())Check results with isinstance(result, BaseException), not Exception. A child that was cancelled yields asyncio.CancelledError, which derives from BaseException. A check against Exception would treat it as a normal result.
| Setting | On a child exception | Other children | Return value |
|---|---|---|---|
| `return_exceptions=False` (default) | First exception is raised from `await` | Keep running, results discarded | Nothing, because the await raised |
| `return_exceptions=True` | Exception becomes a list item | Run to completion | Full list, mixing results and exceptions |
Use return_exceptions=True when failures are expected and independent, such as fetching many URLs where some may fail. Use the default when any failure makes the whole result useless.
Cancelling a gather
Cancelling the future returned by gather cancels every child that has not finished. Each child receives CancelledError at its current await.
import asyncio
async def worker(n):
try:
await asyncio.sleep(10)
except asyncio.CancelledError:
print("worker", n, "cancelled")
raise
async def main():
group = asyncio.gather(worker(1), worker(2))
await asyncio.sleep(0.1)
group.cancel()
try:
await group
except asyncio.CancelledError:
print("group cancelled")
asyncio.run(main())The output is worker 1 cancelled, worker 2 cancelled, then group cancelled.
The reverse does not hold. If one child is cancelled on its own, for example because some other code calls cancel() on a task you passed in, the group is not cancelled. With the default setting, gather raises CancelledError to your code. With return_exceptions=True, the CancelledError appears in the result list.
Cancelling the task that is awaiting gather also cancels the children. This is the mechanism that makes asyncio.wait_for(asyncio.gather(...), timeout=2) clean up its children when the timeout expires. The timeouts chapter covers this in more detail.
Edge cases
- Passing tasks or futures.
gatheraccepts them as well as coroutines. Tasks that already exist are not wrapped again. Passing the same task twice is allowed and returns its result twice. - Passing the same coroutine object twice. This fails, because a coroutine can only be awaited once. Call the coroutine function twice to get two coroutine objects.
- Tasks start at the call, not at the await. Coroutines are scheduled as tasks as soon as you call
gather(...). They begin running at the next point where the current task yields to the loop, even if you await the result later. In the cancellation example above,groupis created before thesleep(0.1), and the workers start during that sleep. - Blocking children. Because everything shares one thread, a child that calls
time.sleepor does heavy computation stalls all the others.gatherdoes not give you parallelism. It interleaves work atawaitpoints. - Nested gathers. A
gathercan be a child of anothergather. The inner result list appears as one item in the outer list, which is useful for grouping related work.
Choosing between gather and TaskGroup
gather is concise when you want a list of results. Its weakness is that cancelling siblings after a failure is your job, and only one exception reaches you. On Python 3.11 and later, asyncio.TaskGroup cancels the remaining tasks when one fails and reports every failure together. The next chapter covers it. A practical rule: use gather for quick fan-out where failures are rare or collected with return_exceptions=True, and prefer TaskGroup when a failure should stop the whole group.
Exercise
You run results = await asyncio.gather(a(), b(), c(), return_exceptions=True). Task b takes 0.1 s and raises KeyError, task a takes 0.5 s and returns "A", and task c takes 0.3 s and returns "C". How long does the await take, and what does results contain?
Show answer
The await takes about 0.5 s, because gather waits for every child even after b fails. results is ["A", KeyError(...), "C"]. The list follows the argument order a, b, c. It does not follow completion order. The KeyError is a list item and is not raised.
Exercise
A teammate writes await asyncio.gather(*(process(item) for item in items)) and finds that after one item raises, the other items still write to the database. Why does this happen, and name two ways to fix it?
Show answer
With the default settings, gather raises the first exception but does not cancel the other children, so they continue running. One fix is return_exceptions=True, which waits for all of them and lets you inspect each outcome. Another is to keep the tasks from create_task, catch the exception, and call cancel() on the remaining tasks. A third is asyncio.TaskGroup on Python 3.11 and later, which cancels siblings on failure.