Sobes.tech
Middle

What is a wait() function?

sobes.tech AI

Answer from AI

In the context of asynchronous programming in Python using the asyncio module, the asyncio.wait() function is used to wait for multiple coroutines to complete.

Main aspects:

  • Returns two tuples: (done, pending).
    • done: A set of coroutines that have finished (returned a result, raised an exception, or were canceled).
    • pending: A set of coroutines that have not yet finished.
  • Accepts an iterable of coroutines (or objects awaiting completion, such as tasks).
  • Allows controlling the completion conditions:
    • return_when: Determines when wait should return. It can be asyncio.FIRST_COMPLETED, asyncio.FIRST_EXCEPTION, asyncio.ALL_COMPLETED (default value).
    • timeout: Maximum waiting time in seconds. If some tasks do not finish within this time, they are placed in the pending set.
  • Unlike asyncio.gather(), which returns results as a list after all coroutines complete, asyncio.wait() returns sets of completed and pending coroutines and does not automatically collect results.

Example usage:

import asyncio

async def coro1():
    await asyncio.sleep(1)
    print("coro1 finished")
    return "Result 1"

async def coro2():
    await asyncio.sleep(2)
    print("coro2 finished")
    # raise ValueError("Something went wrong")
    return "Result 2"

async def main():
    task1 = asyncio.create_task(coro1())
    task2 = asyncio.create_task(coro2())

    # Wait for all tasks to complete
    done, pending = await asyncio.wait([task1, task2], return_when=asyncio.ALL_COMPLETED)

    print("Wait finished")

    for task in done:
        try:
            result = task.result()
            print(f"Task result: {result}")
        except Exception as e:
            print(f"Task raised exception: {e}")

asyncio.run(main())