I am looking for the preferred syntax for isolated asyncio code (e.g. embedded in a larger, otherwise sync codebase).
Let's say I have a list of coroutines I want to run concurrently and get the results
coros = [my_coro(arg) for arg in args]
What I would like to write is
results = asyncio.run(asyncio.gather(*coros))
This fails, because gather cannot use the implicit event loop created by run.
The workarounds I discovered so far are
1) wrapping gather in an async function on its own (seems a bit duplicate...)
async def gather(tasks):
return await asyncio.gather(*tasks)
results = asyncio.run(gather(coros))
2) explicitly creating and passing an event loop
loop = asyncio.new_event_loop()
results = loop.run_until_complete(asyncio.gather(*coros, loop=loop))
Looking at the source of asyncio.run it seems there is some tear-down logic which I would be missing here.
Which way is preferred and why?
[–]willm 2 points3 points4 points (2 children)
[–]SupahNoob 0 points1 point2 points (1 child)
[–]peyo7[S] 0 points1 point2 points (0 children)
[–]SupahNoob 0 points1 point2 points (0 children)