Next / Previous / Contents / TCC Help System / NM Tech homepage

18.2. Generators

Generators are a completely new type of iterator that allows a function to do lazy evaluation of a sequence, that is, to produce the values of the sequence one by one on demand.

Normally, when a function it is called, it runs until it either provides a value with a return statement, or falls off the bottom of the function block. But starting in Python 2.2, it is possible for a function to return a value and also suspend its entire internal state for later resumption. This state includes the current point of execution inside the function, and all its local variables. Such a function is called a generator.

A generator G can be used in a for statement:

for v in G():
    B

In this context, every time the generator G returns a value, v is set to that value, and the block B is executed.

The beauty of this construct is that function G doesn't have to compute all its values at once. It can do lazy evaluation, producing new values only as they are needed by the caller.

To write your own generator, you must have this special import statement to enable the feature:

from __future__ import generators

In your function definition, use the yield statement to generate the next value:

yield E

Executing this statement returns the value of expression E, but it also saves the state of the function to allow later resumption.

Here's an example. This function generates the even numbers from 0 up to the argument you give it:

def evens(n):
    i = 0
    while 2*i <= n:
        yield 2*i
        i = i + 1

Here's how that function would work in a for statement:

>>>for v in evens(30):
...    print v,
...
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30