0

I'm learning about asycio and trying to run this script I get this error:

ValueError: a coroutine was expected, got <async_generator object mygen at 0x7fa2af959a60>

What am I missing here?

import asyncio

async def mygen(u=10):
     """Yield powers of 2."""
     i = 0
     while i < int(u):
         yield 2 ** i
         i += 1
         await asyncio.sleep(0.1)

asyncio.run(mygen(5))
JON
  • 127
  • 1
  • 10
  • 1
    Your problem is the use of `yield`. You need to iterate over the generator with `async for`. `asyncio.run` won’t do that for you. – dirn Feb 17 '22 at 20:49

1 Answers1

2

The asyncio.run function expects a coroutine but mygen is an asynchronous generator.

You can try something like this:

test.py:

import asyncio


async def mygen(u=10):
    """Yield powers of 2."""
    i = 0
    while i < int(u):
        yield 2**i
        i += 1
        await asyncio.sleep(0.1)


async def main():
    async for i in mygen(5):
        print(i)


if __name__ == "__main__":
    asyncio.run(main())

Test:

$ python test.py 
1
2
4
8
16

References:

HTF
  • 6,632
  • 6
  • 30
  • 49
  • Can you provide any input on this one : https://stackoverflow.com/questions/71169287/asyncio-and-paramiko-for-concurrent-ssh-connectivity – JON Feb 18 '22 at 06:43