while-looppython-asyncio

implementing while loop in asyncio program that does not call any coroutines


In my asyncio program I have a while loop:

while condition:
   do this
   do that

but none of this or that requires any async functions and at the end of the loop I want to await something and jump back into the event loop. I'm sure I could use asyncio.sleep(0) at the end of the loop and it would work just fine or just create my own async pass function. I'm just wondering if there is any 'built-in' way of doing that? Using asyncio.sleep(0) just feels like a bit of a hack.

while condition:
   do this
   do that
   await asyncio.sleep(0)

Solution

  • It might feel like a hack, but it is a the recommended way to avoid running a blocking loop on the event loop.

    Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.

    https://docs.python.org/3/library/asyncio-task.html#asyncio.sleep