For those that may have heard about generators but aren't too familiar with them or what they do, Torben Köhn has posted a great introduction to them and their functionality.
In my in-depth guide about iterators I talked about what iterators are exactly and how you can use them. At the end I told you that I’ll also write one for generators. Here it is.First off, if you don’t know what an iterator is and you’d not be able to explain to someone else what it is, you will not have much fun with this because you won’t exactly recognize the use-cases. I suggest you read my iterator-guide first. After this, don’t get scared off by some confusing words used here, I’ll try to clarify every single one.
He breaks up the rest of the post into different sections, each walking you through different aspects of generators:
- What is a generator?
- The yield-keyword
- Iterating a generator
- Yielding keys
- Yielding in a loop
- An infinite generator
He wraps up the post sharing some real use-cases for generators to help you understand them with a bit more practical application (including stacking them, file system handling and co-routines).