Junior — Middle
What is the purpose of the gather function in the asyncio module in Python?
sobes.tech AI
Answer from AI
The asyncio.gather function in Python is used to run multiple coroutines concurrently and collect their results. It takes several awaitable objects (coroutines, tasks, or futures) and returns a single awaitable that completes when all the provided tasks are finished. The result will be a tuple containing the results of all coroutines in the same order.
Example:
import asyncio
async def task(n):
await asyncio.sleep(n)
return f"Task {n} completed"
async def main():
results = await asyncio.gather(task(1), task(2), task(3))
print(results)
asyncio.run(main())
In this example, three tasks run in parallel, and gather collects their results into a list.