Python 3, an Illustrated Tour Transcripts
Chapter: Asynchronous Programming
Lecture: Walk-through: Asyncio Generators

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 async gen test, open that up in your editor. And this is about making asynchronous generators.
0:08 So it says write an a synchronous generator countdown that accepts a count and a delay, when looped over asynchronously,
0:14 it returns the numbers from countdown to an including zero it waits for delay seconds before returning the next value.
0:20 This should be very familiar to you if you've already done async iter test. So let's make a generator that does this
0:28 the point of this is to show that generators are typically easier to implement and easier to debug than iterators.
0:35 So in order to make an a synchronous generator we say async def and it's going to be called countdown, it's going to accept count and delay
0:44 and I'm just going to go into a while loop here, I am going to say while 1 and I will yield count and if count equals 0 then I will break out of here.
0:59 Otherwise, I will say count minus equals 1 and then I'm going to sleep
1:05 and I could just say time.sleep, but that's not going to be an asynchronous sleep. So in order to do an asynchronous sleep,
1:11 I need to import the asyncio library and then we need to await it. So we're going to call await asyncio.sleep.
1:23 and we're going to sleep for delay seconds again because I am in an asynchronous generator, I can call await on an asynchronous function here
1:34 and that should be it, let's give it a test and make sure that it works here.
1:38 So just run it here, it takes a while because it's doing some delaying here, but it looked like it ran.
1:47 This is the same test code basically as async iter test and note that it takes 2 seconds to run
1:52 and if we come down here we say that we're counting down from 2 with 1 second delay. So that should take 2 seconds to run.
1:58 You'll note that we're sort of unrolling the asynchronous iteration protocol down here and asserting that we raise a stop async iteration error
2:07 You'll note that we don't explicitly raise that exception but when the generator returns that raises the exception for us,
2:13 so thanks for watching this video. Hopefully you have a better feel for those a synchronous generators now
2:19 and you can hopefully take advantage of those and use those in your code.

Talk Python's Mastodon Michael Kennedy's Mastodon