Defining a Generator

The presence of the yield statement in a function means that the function is actually a generator object, and will have the an iterator-like interface built automatically. In effect it becomes a stateful object with a next method defined — so it will work with the for statement — and it will raise the StopIteration exception when it returns.

The syntax for a function definition is in the section called “Function Definition: The def and return Statements”; a generator is similar.

def name ( 〈 parameter ...〉 ): suite

The suite of statements must include at least one yield statement.

The yield statement specifies the values emitted by the generator. Note that the expression is required.

yield expression

If the return statement is used, it ends the generator, and raises the StopIteration exception to alert the for statement. For obvious reasons, the return statement cannot return a value.

Here's a complete, but silly example of a generator.

def primes():
    yield 2
    yield 3
    yield 5
    yield 7
    yield 11
    return

In this case, we simply yield a fixed sequence of values. After yielding five values, it exits. Here's how this generator is used by a for statement.

>>> 
for p in primes():
...     print p



2
3
5
7
11