asynchronous python itertools chain multiple generators

若如初见. 提交于 2019-12-02 07:53:28

The async equivalent of next is the __anext__ method on the async iterator. The iterator is in turn obtained by calling __aiter__ (in analogy to __iter__) on an iterable. Unrolled async iteration looks like this:

a_iterator = obj.__aiter__()          # regular method
elem1 = await a_iterator.__anext__()  # async method
elem2 = await a_iterator.__anext__()  # async method
...

The __anext__ method will raise StopAsyncIteration when no more elements are available. To iterate over async iterators, you should use async for rather than for.

Here is a runnable example, based on your code, using both __anext__ and async for to exhaust the stream set up with aiostream.stream.combine.merge:

async def main():
    a_mix = stream.combine.merge(gen1(), gen2())
    async with a_mix.stream() as streamer:
        mix_iter = streamer.__aiter__()    
        print(await mix_iter.__anext__())
        print(await mix_iter.__anext__())
        print('remaining:')
        async for x in mix_iter:
            print(x)

asyncio.get_event_loop().run_until_complete(main())
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!