【协程】9、asyncio异步迭代器

1、什么是异步迭代器

  • 实现了__aiter__()和__anext__()方法的对象。__anext__必须返回一个awaitable对象。async for会处理异步迭代器的__anext__()方法所返回的可等待对象,直到引发一个StopAsyncIteration异常。由PEP 492引入。

2、什么是异步可迭代对象

  • 可在async for语句中被使用的对象。必须通过它的__aiter__()方法返回一个asynchronous iterator。由PEP 429引入。

3、示例:

# -*- coding: utf-8 -*-
import asyncio


class Reader(object):
    """ 自定义异步迭代器(同时也是异步可迭代对象) """

    def __init__(self):
        self.count = 0

    async def readline(self):
        self.count += 1
        if self.count == 100:
            return None
        return self.count

    def __aiter__(self):
        return self

    async def __anext__(self):
        val = await self.readline()
        if val == None:
            raise StopAsyncIteration
        return val


async def func():
    obj = Reader()
    async for item in obj:
        print(item)

asyncio.run(func())
posted @ 2022-05-31 14:09  郭祺迦  阅读(70)  评论(0)    收藏  举报