So, as @bosnjak said, you can use async for:
async for ITEM in A_ITER: BLOCK1 else: # optional BLOCK2
But if you want to iterate manually, you can simply write:
it = async_iterator() await it.__anext__()
But I would not recommend doing this.
I think that if you are going to call something Iterator your own, because it has exactly the same interface, so I can just write asynchronous iterators and use them in a structure that depends heavily on the following () calls
No, this is not the same. There is a difference between regular synchronous iterators and asynchronous. And there are several reasons for this:
- Python consoles are built on top of built-in generators.
- According to Zen python, explicit is better than implicit. So you really see where the code can be paused.
This is why it is not possible to use iter and next with asynchronous iterators. And you cannot use them with frameworks waiting for synchronous iterators. Therefore, if you intend to make your code asynchronous, you also need to use asynchronous frameworks. There are few of them.
In addition, I would like to say a few words about iterators and generators. An iterator is a special object that has the __iter__ and __next__ . While the generator is a special function containing the expression yield . Each generator is an iterator, but not vice versa . The same is acceptable for asynchronous iterators and generators. Yes, with python 3.6 you can write asynchronous generators!
async def ticker(delay, to): for i in range(to): yield i await asyncio.sleep(delay)
Learn more about PEP 525
source share