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 can be used
in a Gfor statement:
forvinG():B
In this context, every time the generator
returns a value,
G is
set to that value, and the block
v is
executed.B
The beauty of this construct is that function
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.G
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 EExecuting this statement returns the value of
expression
, but it
also saves the state of the function to allow later
resumption.E
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 + 1Here'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