Now we come on to generator functions, one of the most powerful and elegant features of the Python programming language. Python generators provide the means for describing iterable series with code in functions. These sequences are evaluated lazily, meaning they only compute the next value on demand. This important property allows them to model infinite sequences of values with no definite end, such as streams of data from a sensor or active log files. By carefully designing generator functions we can make generic stream processing elements which can be composed into sophisticated pipelines.
Generators are defined by any Python function which uses the yield
keyword at least once in its definition. They may also contain the return
keyword with no arguments, and just like any other function, there is an implicit return at the end of the definition.
To understand what generators do, let's start with a simple example at the Python REPL. Let's define the generator...