Python 3, an Illustrated Tour Transcripts
Chapter: Asynchronous Programming
Lecture: asyncio Context Iterators

Login or purchase this course to watch this video and the rest of the course contents.
0:00 In this video we're going to look at asynchronous iterators. These were described in pep 492, it came out in Python 3.5.
0:07 Again, here's the protocol for asynchronicity, we can make co-routines and we saw that we can define those with async def.
0:16 You can also define a class that's awaitable, if you implement the __await__ method we can make iterators by defining two methods here.
0:24 We can define __aiter__ and __anext__. These are analogous to iterators in normal Python, in synchronous Python where we define __iter__ and __next__.
0:36 Here, we're going to show an example of an asynchronous iterator. This is implementing a basic version of range,
0:42 it's just going to do it asynchronously. So we're going to make a class called Arange, it's going to have a constructor that takes a start and an end
0:48 and the end is optional, if the end is not set, then we use the start as the end value when we start at 0. We're going to define two methods in here,
0:56 one is called __aiter__ and the other one is called __anext__ Note that __anext__ is a coroutine, we're defining it with async and aiter,
1:06 you can see in the implementation of the coroutine __anext__ that we look at our current value of start and if it's greater than or equal to the end
1:15 then we raise a stop async iteration. This is analogous to stop iteration in non asynchronous land
1:22 and if that isn't the case, we're going to increment the start value and we're going to return the value there.
1:28 So this should count up up to but not including the end number. Here's an example of running arange.
1:35 We've got a routine called run arange and note that we have a for loop here in front of our for loop we have async
1:41 so because this is the asynchronous iteration we need to put async in front of our for loop we can get our event loop and then say run until complete
1:50 and this will print out the numbers from 0 up to but not including 5 asynchronous iterators are pretty straightforward,
1:57 again, you just need to implement that __aiter__ and a coroutine called __anext__ and you can make something that you can use in asynchronous land.

Talk Python's Mastodon Michael Kennedy's Mastodon