2.4 Lazy and eager evaluation
Python’s generator expressions and generator functions are lazy. These expressions don’t create all possible results immediately. It’s difficult to see this without explicitly logging the details of a calculation. Here is an example of the version of the range()
function that has the side effect of showing the numbers it creates:
from collections.abc import Iterator
def numbers(stop: int) -> Iterator[int]:
for i in range(stop):
print(f"{i=}")
yield i
To provide some debugging hints, this function prints each value as the value is yielded. If this function were eager, evaluating numbers(1024)
would take the time (and storage) to create all 1,024 numbers. Since the numbers()
function is lazy, it only creates a number as it is requested.
We can use this noisy numbers()
function in a...