Junior — Middle
What are the features of the gather function in the asyncio library and what are its advantages in organizing asynchronous operations?
sobes.tech AI
Answer from AI
The asyncio.gather function is used to run multiple coroutines concurrently and wait for their completion. It takes several awaitable objects and returns their results as a list, maintaining the order of invocation.
Advantages of gather:
- Allows running multiple asynchronous tasks simultaneously, increasing efficiency.
- Simplifies managing a group of tasks, as you can wait for all of them with a single call.
- Supports exception handling: if one task fails,
gathercan raise an exception or continue execution depending on parameters.
Example usage:
import asyncio
async def fetch_data(x):
await asyncio.sleep(1)
return x * 2
async def main():
results = await asyncio.gather(
fetch_data(1),
fetch_data(2),
fetch_data(3)
)
print(results) # [2, 4, 6]
asyncio.run(main())