Middle+
What is the gather() function?.
sobes.tech AI
Answer from AI
asyncio.gather() combines the results of multiple asynchronous objects (coroutines, tasks) and returns an iterator or a single result after all objects have completed. This is useful for running independent asynchronous operations in parallel.
Key features:
- Concurrent execution: Runs all passed objects simultaneously.
- Order preservation: The order of results corresponds to the order of the passed objects.
- Exception handling: By default, if any object raises an exception,
gather()propagates it. Thereturn_exceptions=Trueparameter allows collecting exceptions into a list of results instead of stopping execution. - Input types: Accepts an iterable (list, tuple, etc.) of asynchronous objects.
Applications:
- Parallel data loading from different sources.
- Executing multiple independent network requests.
- Handling multiple tasks that can run concurrently.
import asyncio
async def task1():
await asyncio.sleep(1)
return "Result 1"
async def task2():
await asyncio.sleep(2)
return "Result 2"
async def main():
results = await asyncio.gather(task1(), task2())
print(results) # Will output ['Result 1', 'Result 2']
asyncio.run(main())