1

How do I get around the chicken and egg issue here?

One function will return the first result of a generator, this generator must gather data from the function that called it. This works in general code, but as soon as you throw async in the loop (I don't want to return a coroutine) it errors out. How do I not return a coroutine from function_one?

Code:

import asyncio

async def second_iterator(number):
    for x in range(number):
        yield await function_one(x)

async def function_one(number):
    if number > 2:
        return asyncio.run(second_iterator(number))

    await asyncio.sleep(1)
    return number

def main(number):
    print(asyncio.run(function_one(number)))

main(3)

Error:

Traceback (most recent call last):
  File "main.py", line 17, in <module>
    main(3)
  File "main.py", line 15, in main
    print(asyncio.run(function_one(number)))
  File "C:\Users\Owner\Anaconda3\lib\asyncio\runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "C:\Users\Owner\Anaconda3\lib\asyncio\base_events.py", line 579, in run_until_complete
    return future.result()
  File "main.py", line 9, in function_one
    return asyncio.run(second_iterator(number))
  File "C:\Users\Owner\Anaconda3\lib\asyncio\runners.py", line 34, in run
    "asyncio.run() cannot be called from a running event loop")
RuntimeError: asyncio.run() cannot be called from a running event loop
ben.weller
  • 33
  • 6
  • 1
    Why don't you asynchronously iterate over the asynchronous iterator? What value do you expect ``asyncio.run(second_iterator(number))`` to resolve to? What is the non-async version of this code? – MisterMiyagi Feb 06 '20 at 16:56

1 Answers1

0

You should have only single asyncio.run() in your script. It's sort of entry point of a program:

import asyncio


async def main():
    # all your code is here


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

asyncio.run() is the only blocking operation that starts event loop that manages execution of all of your coroutines and tasks.

Please consider reading some tutorial on asyncio, it may help you to achieve your goal faster:

Mikhail Gerasimov
  • 36,989
  • 16
  • 116
  • 159