Home > Software design >  How to await a list of tasks in python?
How to await a list of tasks in python?

Time:06-12

In .Net c# there is a function Task.WhenAll that can take a list of tasks to await them. What should I use in python? I am trying to do the same with this:

tasks = ... #list of coroutines

for task in tasks:
 await task

CodePudding user response:

Use asyncio.gather if you're on Python 3.7 or above. From the docs:

Run awaitable objects in the aws sequence concurrently. If any awaitable in aws is a coroutine, it is automatically scheduled as a Task. If all awaitables are completed successfully, the result is an aggregate list of returned values. The order of result values corresponds to the order of awaitables in aws.

CodePudding user response:

After adding tasks to a list, you should use asyncio.gather that gives coroutines as an argument list and executes them asynchronously. Also, you could use asyncio.create_task that gives a coroutine and calls concurrent tasks in the event loop.

import asyncio


async def coro(i):
    await asyncio.sleep(i//2)


async def main():
    tasks = []
    for i in range(5):
        tasks.append(coro(i))
    await asyncio.gather(*tasks)


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    loop.close()
  • Related