Python Jumpstart by Building 10 Apps Transcripts
Chapter: App 8: File Searcher App
Lecture: Core concept: Generator methods
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
Let's look at this core concept of generator methods. Here we have a Fibonacci method and we are passing the limit to it,
0:09
to say how many numbers do we want, in traditional type of methods you could have a list and we could go through
0:15
and compute all the items adding them to the list and then when all the answers are done, the entire lists are generated,
0:21
we could then return that list. Generator methods provide us a different mechanism,
0:27
a different way to do that, it dramatically different performance characteristics. Here what we do is we come to this method and we work our way down
0:35
just like any regular method until we get to the yield keyword, and the yield keyword says here is an item in our collection,
0:40
and immediately this method is sort of suspended, the item is returned to whoever called this function as the next item in the sequence,
0:49
they can process it and either decide to continue pulling on the sequence from like a foreign loop or something or they can stop and that's it,
0:57
you've only computed one item. But if they come back and they ask for the next one
1:00
then execution will resume right here, and it just goes around, gives the item back,
1:05
the caller looks at it and it gives you this kind of lazy evaluation of items
1:10
that ultimately turn into sequences where the sequences don't have to be stored in memory all at once before you get to work with them,
1:18
so these generator methods and this yield keyword are really powerful when you are processing large sets of data in series
1:25
or you are even building pipelines where one step pulls on some large data source and then another step takes that process transformed,
1:32
filtered a bit and does more work on it and then you keep doing that and passing along until finally some sort of pipeline spits out
1:39
a smaller transformed set of items, the composition of generator methods is amazing there.
1:44
And that's what we are going to build in our file searcher app, when we get back to it.