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?
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With