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?
Vasili Pascal :
https://www.python.org/dev/peps/pep-0525/#asynchronous-generator-object\nan example function you can use instead range():\nasync def async_range(count):\n for i in range(count):\n yield(i)\n await asyncio.sleep(0.0)\n",
2018-08-10T08:09:47
Jesse Bakker :
This should do it:\n\nasync def myrange(start, stop=None, step=1):\n if stop:\n range_ = range(start, stop, step)\n else:\n range_ = range(start)\n for i in range_:\n yield i\n await asyncio.sleep(0)\n",
2018-07-25T18:46:01