异步迭代器:
实现了 __aiter__() 和 __anext__() 方法的对象。__anext__ 必须返回一个 awaitable 对象。async for 会处理异步迭代器的 __anext__() 方法所返回的可等待对象,直到其引发一个 StopAsyncIteration 异常。
异步迭代对象:
可在 async for 语句中被使用的对象。必须通过它的 __aiter__() 方法返回一个 asynchronous iterator
例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import asyncio class Reader(object): """ 自定义一个异步迭代器,同时也是一个异步迭代对象 """ def __init__(self): self.count = 0 async def readline(self): #这里不能去掉async,因为去掉就不是协程对象 self.count += 1 if self.count == 10: return None return self.count def __aiter__(self): return self async def __anext__(self): val = await self.readline() if val is None: raise StopAsyncIteration return val async def main(): r = Reader() async for item in r: #async for 必须在async def中 print(item) if __name__ == '__main__': asyncio.run(main()) |
