I have a python script with a running asyncio event loop, I want to know how to iterate over a large list without blocking the event loop. Thus keeping the loop running.
I've tried making a custom class with __aiter__
and __anext__
which did not work, I've also tried making an async function
that yields the result but it still blocks.
Currently:
for index, item in enumerate(list_with_thousands_of_items):
# do something
The custom class I've tried:
class Aiter:
def __init__(self, iterable):
self.iter_ = iter(iterable)
async def __aiter__(self):
return self
async def __anext__(self):
try:
object = next(self.iter_)
except StopIteration:
raise StopAsyncIteration
return object
But that always results in
TypeError: 'async for' received an object from __aiter__ that does not implement __anext__: coroutine
The async function
I made which works but still blocks the event loop is:
async def async_enumerate(iterable, start:int=0):
for idx, i in enumerate(iterable, start):
yield idx, i