Implementing aiter and anext
00:00
In the previous lesson, you learned that an async iterable implements the __aiter__ special method and an async iterator additionally implements the __anext__ special method.
00:12
So it makes sense to start with the __aiter__ special method and have a look at how to implement that. So a __aiter__ special method must return an async iterator.
00:24
But hang on, the __aiter__ special method is implemented by an iterable too. So are those two related? Well, yes, they are. You can think of it this way. An iterable holds the data that can be iterated over and to then actually iterate over your iterable, you call the __aiter__ special method on the iterable to give you the object that controls that iteration process and that object, as you know, is your iterator.
00:54
So let’s then move on to the iterator, which additionally implements the __anext__ special method. So the __anext__ special method must return the next element of the async iterable, if that makes sense.
01:07
It also must return an awaitable object. I guess that makes sense because we’re working asynchronously, and it must raise a StopAsyncIteration exception when the data stream is exhausted.
01:21
So you can see how the implementation of __anext__ controls the iteration process. Well, firstly, it provides the next elements in the loop and then it stops the loop when there are no more elements to iterate over.
01:36
Okay, so how do you use these things then? Well, you use them in asynchronous loops as you might have expected. So async for loops, for example.
01:44
And then in terms of use, I’d like to finally remind you of the key point of async iteration, and that is to provide non-blocking iteration. So what that means is that the running of an async loop, such as async for, doesn’t block the code from running other async tasks or loops.
02:05 So to hammer these concepts home and to see how they are being used in practice, you are going to introduce async iteration in your code example in the next lesson.
Become a Member to join the conversation.
