gather
- Python course
- Advanced
- Lesson 31/83
- 5 min
Learn to await multiple coroutines with asyncio.gather.
gather
asyncio.gather launches many coroutines at once and waits for all of them to finish. It returns their results as a list in the order given.
import asyncio
async def fetch(n):
return n * 2
async def main():
results = await asyncio.gather(fetch(1), fetch(2), fetch(3))
return results # [2, 4, 6]gather starts each call in turn; it awaits until all complete. If one raises, gather raises by default; with return_exceptions=True errors come back in the result list.
return_exceptions and errors
If one of the coroutines passed to gather raises, by default gather raises too. This is good for fast failure.
But if you want to see all results (including errors), use return_exceptions=True. The error objects appear in the result list; you can continue processing.
results = await asyncio.gather(
fetch(1), bad_fetch(),
return_exceptions=True)This option is useful when partial success matters.
Practice Parallel fetch with gather
Start with import asyncio. The function async def fetch(n) returns n * 2. Inside async def main() call await asyncio.gather(fetch(1), fetch(2), fetch(3)) and return it. Add print(asyncio.run(main())).
Starter code
# import the asyncio module
# declare a coroutine named fetch; return n doubled
# main coroutine awaits three fetch calls via gather
# print the result of main via asyncio.runSample solution
import asyncio
async def fetch(n):
return n * 2
async def main():
return await asyncio.gather(fetch(1), fetch(2), fetch(3))
print(asyncio.run(main()))Expected output
[2, 4, 6]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In what order does asyncio.gather return results?
- By completion order
- By call order Correct answer
- In random order
- It returns only the first result
Explanation: gather returns results by call order; completion order does not matter.
2 gather call
import asyncio
async def main():
return await asyncio.____(fetch(1), fetch(2))
import asyncio
async def main():
return await asyncio.gather(fetch(1), fetch(2))
Explanation: asyncio.gather(...) awaits many coroutines.
3 Match the gather concepts
| Term | Meaning |
|---|---|
gather(*coros) |
Awaits all |
call order |
Result order |
return_exceptions=True |
Puts errors in list |
await gather(...) |
Waits for completion |