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))
1
  • 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. Commented Feb 17, 2022 at 20:49

1 Answer 1

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:

Sign up to request clarification or add additional context in comments.

1 Comment

Can you provide any input on this one : stackoverflow.com/questions/71169287/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.