Middle
What is the gather() function in Python and when should it be used?
sobes.tech AI
Answer from AI
asyncio.gather() combines multiple asynchronous objects (awaitable) into a single Future.
Use the gather() function:
- When you need to run several coroutines or other asynchronous tasks in parallel and wait for all of them to complete.
- To group the results of asynchronous operations.
- To handle exceptions that occur in any of the combined tasks.
Example usage:
import asyncio
async def task_one(delay):
# Simulate a long operation
await asyncio.sleep(delay)
return f"Task one finished after {delay} seconds"
async def task_two(data):
# Simulate data processing
await asyncio.sleep(1)
return f"Task two processed: {data}"
async def main():
results = await asyncio.gather(
task_one(2),
task_two("some_data"),
return_exceptions=True # Returns exceptions instead of raising them
)
print(results)
# Run the main coroutine
# asyncio.run(main())