How to Use asyncio.gather in Python for Concurrent Tasks
Use
asyncio.gather to run multiple asynchronous tasks concurrently in Python. It takes multiple awaitable objects and returns their results as a list once all complete.Syntax
The basic syntax of asyncio.gather is:
asyncio.gather(*tasks, return_exceptions=False)- *tasks: One or more awaitable objects (like async functions or coroutines).
- return_exceptions: Optional boolean; if
True, exceptions are returned as results instead of raising.
This function runs all tasks concurrently and waits for all to finish, returning their results in order.
python
asyncio.gather(*tasks, return_exceptions=False)Example
This example shows how to run two async functions concurrently using asyncio.gather and get their results together.
python
import asyncio async def say_after(delay, message): await asyncio.sleep(delay) return message async def main(): task1 = say_after(2, 'hello') task2 = say_after(1, 'world') results = await asyncio.gather(task1, task2) print(results) asyncio.run(main())
Output
['hello', 'world']
Common Pitfalls
Common mistakes when using asyncio.gather include:
- Not awaiting
asyncio.gatheritself, which means tasks won't run. - Passing non-awaitable objects, causing errors.
- Ignoring exceptions raised by tasks, which can stop all tasks unless
return_exceptions=Trueis used.
Here is an example showing the wrong and right way:
python
import asyncio async def fail(): raise ValueError('Oops') async def main_wrong(): # Missing await - tasks won't run asyncio.gather(fail()) async def main_right(): # Await gather to run tasks and catch exceptions results = await asyncio.gather(fail(), return_exceptions=True) print(results) # To test, run asyncio.run(main_right())
Output
[ValueError('Oops')]
Quick Reference
| Parameter | Description |
|---|---|
| *tasks | Multiple awaitable objects to run concurrently |
| return_exceptions | If True, exceptions are returned as results instead of raised |
| Returns | A list of results in the order tasks were passed |
Key Takeaways
Always await asyncio.gather to run tasks concurrently and get results.
Pass only awaitable objects like async functions or coroutines to asyncio.gather.
Use return_exceptions=True to handle exceptions without stopping all tasks.
Results are returned in the same order as the tasks were passed.
asyncio.gather is useful for running multiple async operations at the same time efficiently.