Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 380
Mia Avatar asked Dec 13 '22 15:12

Mia


2 Answers

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

an example function you can use instead range():

async def async_range(count):
    for i in range(count):
        yield(i)
        await asyncio.sleep(0.0)
like image 187
Vasili Pascal Avatar answered Dec 29 '22 19:12

Vasili Pascal


This should do it:

async def myrange(start, stop=None, step=1):
    if stop:
        range_ = range(start, stop, step)
    else:
        range_ = range(start)
    for i in range_:
        yield i
        await asyncio.sleep(0)
like image 45
Jesse Bakker Avatar answered Dec 29 '22 19:12

Jesse Bakker