Coding an Iterator Example - __aiter__
00:00
Okay, time for some coding. So the idea is that you will be working on the async.py file and you will take the existing example, but you will now introduce subtasks and you will build a task iterator.
00:14 So the subtasks will be captured in separate lists. Now there’s nothing particularly exciting about you watching me type the lists, so I’ll just copy those in.
00:25
You’ve got a list for each main task. So for LAPTOP, COFFEE and for PARCEL, you have a tuple for each of the subtasks.
00:34
The second thing to do is to build the task iterator, and that will be a class. So class TaskIterator in camel case, the idea is that you will be instantiating this class.
00:49
So you will need the __init__ method, which takes self as its first parameter. Then there is name as an input parameter.
00:55
There will also be task_list. And I’m also going to introduce an end input parameter, which I set to five, which means that the iterator will stop by default after five iterations.
01:10
So this __init__ method, all it’s going to be doing is it’s going to assign those input parameters to instance attributes, and then is going to create a counter that will be needed to manage the loop.
01:23
Okay? So self.name = name`,
01:28
self.task_list = task_list,
01:35
self.end = end. So that’s the instance attributes done at least the assignment of the input parameters. So now the next instance attribute is self.counter.
01:49 I’m going to set that equal to zero for now.
01:52
Remember that to build an iterator, you need the implementation of two special methods, one being .__aiter__ and the other one being .__anext__.
02:01
So let’s start with .__aiter__ underscore underscore,
02:07
and that’s an instance method. So it takes self as an input parameter. And if you have a look at the slides again, see what was the requirement of .__aiter__.
02:18
So it must return an async iterator. Okay, so where is our async iterator? Well, we are building a class that will be our async iterator. So all this .__aiter__ method has to do is to return self, which is the instance of this class.
02:37 So just to show you how things work when you run the code. I’m also going to add this line of code here, which will print some information to your terminal.
02:47
And I’m just copy-pasting that. In the next lesson, you’ll build the .__anext__ special method.
Become a Member to join the conversation.
