我有一个带有正在运行的asyncio事件循环的Python脚本,我想知道如何在不阻塞事件循环的情况下遍历一个大列表。因此保持循环运行。
我尝试过使用__aiter__和__anext__创建自定义类,但没有成功,我还尝试了创建一个异步函数来产生结果,但仍然会阻塞。
当前:
我尝试过的自定义类:
但这总是导致的结果。
我制作的
我尝试过使用__aiter__和__anext__创建自定义类,但没有成功,我还尝试了创建一个异步函数来产生结果,但仍然会阻塞。
当前:
for index, item in enumerate(list_with_thousands_of_items):
# do something
我尝试过的自定义类:
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
但这总是导致的结果。
TypeError: 'async for' received an object from __aiter__ that does not implement __anext__: coroutine
我制作的
async function
能够工作,但仍会阻塞事件循环。async def async_enumerate(iterable, start:int=0):
for idx, i in enumerate(iterable, start):
yield idx, i
__aiter__
应该使用def
,而不是async def
。 - user4815162342