Generators and Coroutines – Infinity, One Step at a Time
Generator functions are functions that behave like iterators by generating the return values one by one. While traditional methods build and return a list
or tuple
of items with a fixed length, a generator will yield
a single value only when requested by the caller. The side effect is that these generators can be infinitely large because you can keep yielding forever.
In addition to generators, there is a variation to the generator’s syntax that creates coroutines. Coroutines are functions that allow multitasking without requiring multiple threads or processes. Whereas generators can only yield values to the caller based on the initial arguments, coroutines enable two-way communication with the calling function while running. The modern implementation of coroutines in Python is through the asyncio
module, which is covered extensively in Chapter 13, asyncio – Multithreading without...