Implementing an asynchronous iterator

前端 未结 2 1824
一个人的身影
一个人的身影 2021-01-06 19:35

Per PEP-492 I am trying to implement an asynchronous iterator, such that I can do e.g.

async for foo in bar:
    ...

Here is a trivial exa

2条回答
  •  清酒与你
    2021-01-06 20:01

    Asynchronous iterators have been implemented in Python 3.6 - see PEP-525

    Then you don't need your TestImplementation at all in order to use async for. You can just use yield (example taken from PEP-525):

    async def ticker(delay, to):
        """Yield numbers from 0 to `to` every `delay` seconds."""
        for i in range(to):
            yield i
            await asyncio.sleep(delay)
    

    You can then use async for as you would expect:

    async for i in ticker(1, 10):                                                                     
        print(f'Tick #{i}')
    

提交回复
热议问题