Sobes.tech
Middle+

What is the gather() function?

sobes.tech AI

Answer from AI

asyncio.gather() is a function from the asyncio module that allows you to run multiple awaitable objects (such as coroutines) concurrently and collect their results.

Main features:

  • Concurrent execution: The specified coroutines are started simultaneously.
  • Waiting for completion: gather() waits for all passed coroutines to finish.
  • Collecting results: The results of the coroutines are returned as a list in the same order they were passed to gather().
  • Exception handling: By default, if one coroutine raises an exception, gather() cancels the remaining unfinished coroutines and re-raises the exception. This behavior can be modified with the return_exceptions=True parameter.

Example usage:

import asyncio

async def task_sleep(name, delay):
    # Coroutine simulating work
    print(f"Task {name}: Starting...")
    await asyncio.sleep(delay)
    print(f"Task {name}: Finished")
    return f"Result from {name}"

async def main():
    # Running two coroutines concurrently
    results = await asyncio.gather(
        task_sleep("A", 2),
        task_sleep("B", 1)
    )
    # Printing results
    print(f"Gather results: {results}")

# Running the main coroutine
if __name__ == "__main__":
    asyncio.run(main())

In this example, task_sleep("A", 2) and task_sleep("B", 1) are started almost simultaneously. gather() waits for their completion and collects their return values ("Result from A", "Result from B") into a list.