Issue
Why doesn't asyncio.gather work with a generator expression?
import asyncio
async def func():
await asyncio.sleep(2)
# Works
async def call3():
x = (func() for x in range(3))
await asyncio.gather(*x)
# Doesn't work
async def call3():
await asyncio.gather(func() for x in range(3))
# Works
async def call3():
await asyncio.gather(*[func() for x in range(3)])
asyncio.run(call3())
The second variant gives:
[...]
File "test.py", line 13, in <genexpr>
await asyncio.gather(func() for x in range(3))
RuntimeError: Task got bad yield: <coroutine object func at 0x10421dc20>
Is this expected behavior?
Solution
await asyncio.gather(func() for x in range(3))
This doesn't work because this is passing the generator object as argument to gather
. gather
doesn't expect an iterable, it expects coroutines as individual arguments. Which means you need to unpack the generator.
Answered By - deceze
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.