Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Building on the Iterable Example

00:00 In this lesson, I’d like you to build on the async.py file to include a task iterable, not just a task iterator. So again, you will be building a class and that is called TaskIterable in camel case. The idea again is to instantiate this class.

00:19 So create the __init__ method, take two input parameters, so name and task_list, which in the __init__ method you will assign to the instance attributes.

00:33 So self.name = name and self.task_list = task_list. So no need to introduce self.counter here. Remember, the iterable is a data container.

00:43 It does not control the iteration process. That’s what the iterator does. Now, of course, somehow you will still need to control this iteration process. So remember that the iterable, the only special method it has is __aiter__, so let’s do that.

01:01 And this __aiter__ method has to return an iterator. And so which iterator will you be returning? Well, we have a class called TaskIterator.

01:11 So what you want to do is you want to return an instance of that class. Well, which instance are you going to return? Remember that the TaskIterator class, as you can see on line 24, takes name and task_list as an input parameter.

01:27 And we can just get that from the TaskIterable instance, so self.name and self.task_list.

01:38 So that is the iterable. What you will now need to do is you will need to adjust your run_iterator coroutine to be a run_iterable coroutine.

01:50 So on line 44, if you change that to iterable and also the input parameter will be an iterable, not an iterator. And then line 45, you will have all the subtasks in your iterable.

02:07 And then you also need to adjust lines 46, 47 and 48 accordingly.

02:17 So now you have a coroutine that runs iterable and it prints all sorts of interesting stuff to the terminal while you are running the code. So the last thing to do is to scroll down to the asyncio .gather() section, because now of course you will be multitasking across iterables in lines 64, 65, and 66, not across iterators.

02:42 So run_iterator that doesn’t exist anymore. That will become run_iterable.

02:51 And then the input into the run_iterable async coroutine was an iterable, not an iterator. So you’re going to create an instance of the TaskIterable class, and the inputs remain the same.

03:04 It would be the name of the iterable, and then the list of subtasks.

03:11 So those are the changes you have to make to introduce an iterable to your code. And in the next lesson, you’ll have a look at the output.

Become a Member to join the conversation.