Collect Concurrent Results with gather
Core idea
asyncio.gather awaits several awaitables and returns results in argument order, regardless of completion order. By default an exception is propagated to the caller; other submitted awaitables are not automatically cancelled merely because one fails. With return_exceptions=True, exceptions appear in the result list. Choose the policy deliberately.
import asyncio
async def main(): gate = asyncio.Event() async def first(): await gate.wait() return 'first' async def second(): gate.set() return 'second' print(await asyncio.gather(first(), second()))
asyncio.run(main())second releases first, yet the output follows argument order.
Expected output:
['first', 'second']Inspect mixed outcomes
import asyncio
async def main(): async def good(): return 4 async def bad(): raise ValueError('bad item') results = await asyncio.gather(good(), bad(), return_exceptions=True) print(results[0], type(results[1]).__name__)
asyncio.run(main())The exception is a returned object under this policy.
Expected output:
4 ValueErrorCommon mistake
Do not assume gather provides fail-fast sibling cancellation. With default propagation, siblings may still run while the caller handles the error; asyncio.run shutdown can then cancel pending tasks, which is a separate effect.
Practice
Collect three jobs, one raising ValueError; compare default propagation with return_exceptions=True while ensuring all tasks are observed.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Gather
Check your understanding of gather.
What is printed?
import asyncio
async def main(): async def f(x): return x print(await asyncio.gather(f(3),f(1)))
asyncio.run(main())What is printed?
import asyncio
async def main(): async def fail(): raise KeyError('x') r=await asyncio.gather(fail(),return_exceptions=True) print(type(r[0]).__name__)
asyncio.run(main())Does default gather cancel every sibling on one failure?
What should callers do with return_exceptions=True?