JON
JON

Reputation: 134

ValueError when running simple asyncio script

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))

Upvotes: 0

Views: 833

Answers (1)

HTF
HTF

Reputation: 7260

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:

Upvotes: 2

Related Questions