pythonpython-asyncio

Reuse of same coroutine (asyncio)


I am not sure why I am getting cannot reuse already awaited coroutine in my code.

I am calling this code in a for loop twice

loop = asyncio.get_event_loop()
if loop.is_running():
    task = asyncio.ensure_future(self.async_print_stats(curb, iswhite, full))
else:
    loop.run_until_complete(self.async_print_stats(curb, iswhite, full))

It takes the same else branch twice. It works the first time, and in the sec time, I get the runtime error on the only line of this function:

async def async_print_stats(self, fen, iswhite, full=True):
    print(await self.async_ret_stats(fen, iswhite, full))
          ^

I just don't see how I am waiting on the same coroutine simulatiounsly( like in gather here: Can I await the same Task multiple times in Python? ) , so I don't understand the reason for the error.

I tried creating a task, but it argues the loop isn't running.

UPDATE:

import asyncio 
asyncio.set_event_loop(asyncio.new_event_loop())
loop = asyncio.get_event_loop()
async def tmp():
    await asyncio.sleep(3)
    print('a')
async def func():
    await tmp()
    print('b')

for i in range(2):
    loop.run_until_complete(func())

This code works. But I haven't done anything else really. So at this point I am not sure what could have caused it.


Solution

  • So it is not that interesting , as apperently the error is unrlated.

    I mistakenly did caching of arguments in this case, and the cache would only work for def functions.

    That is why the second time I called it, the flow was different.