Chapter 20. Comprehensions and Generations
This chapter explores a set of advanced function-related tools and topics. Its main subjects are generator functions and their generator expression relatives—user-defined ways to produce results on demand the same way that many built-ins do. Because generators apply the iteration protocol and generator expressions reuse comprehension syntax, this chapter is also partly a follow-up to Chapter 14 (hence its title). We’ll extend these topics to their completion here and demo with larger examples that tie ideas together.
Finally, this chapter provides just enough of an intro to get you started with async coroutines—tools that build on generators, but assume knowledge of parallel programming, which is outside the scope of this book and the needs of most Python learners. You won’t become an async master here, but you’ll get a head start for further explorations.
Iteration and generation in Python also encompasses user-defined classes, but we’ll defer that final part of this story until Part VI, when we study operator overloading. The next chapter continues threads spun here by timing the relative performance of some of this chapter’s tools as a larger case study. Before that, though, let’s pick up the comprehensions and iterations story where it was last left, and extend it to include value generators.
Comprehensions: The Final Act
As mentioned early in this book, Python supports the procedural, object-oriented, and function programming paradigms. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access