Search code examples
pythonasynchronouspython-3.6

How to iterate over a range asynchronously


In python3.6, if I want to iterate over a range, I can simply do this

for i in range(100): pass

However, what should I do if I want to iterate over a range asynchronously? I can not do

async for i in range(100): pass # Doesn't work

because range is not an AsyncIterable object. One solution I can think about is to subclass range and define __aiter__ method. However it feels really not pythonic for me. Is there any good way/library to do this without defining my own class?


Solution

  • https://www.python.org/dev/peps/pep-0525/#asynchronous-generator-object

    An asynchronous function you can use instead of range():

    async def async_range(count):
        for i in range(count):
            yield i
            await asyncio.sleep(0.0)