7.15 Generators
Closely related to an iterator is the Python concept of a generator. A generator g is a special function with this behavior:
- The first time you call g, it initializes itself, passes back a value, and freezes its state.
- The next time you call g, it continues processing until it passes back a value and then freezes its state again.
- These actions continue until the function terminates, and then it returns no additional values.
We use yield
to tell
Python to pass back a value and freeze everything until the next call to the generator.
def create_odd_number_generator():
n = 1
while True:
yield n
n += 2
odd_number_generator = create_odd_number_generator()
odd_number_generator
<generator object create_odd_number_generator at 0x0000024A93102660>
next(odd_number_generator)
1
next(odd_number_generator)
3
...