Generators behave as though they have three methods. In the
following summaries, g is the generator (or
iterator) object.
g(.next)
The next method resumes execution
after the yield statement. This is called
automatically by the for statement. The
next method does one of two
things:
It raises StopIteration.
An iterator created from a built-in container (sequence,
set, dict, file)
does this at the end of the sequence. A generator does this
when it returns; either because it finished the suite of
statements, or it executed an explicit
return statement. This exception is handled
automatically by the for statement.
It changes its internal state and yields the next value.
An iterator updates its positions in the given container. A
generator, hopefully, is designed properly to update its
internal state and make progress toward completion. It is
possible to mis-design a generator so that it never
terminates.
g(.close)
The close method will force the
generator to stop prematurely. This raises a
GeneratorExit within the generator.
If the generator has acquired resources (like a file, socket, lock
or database connection), it should use a try
statement. When the close method raises an
exception, the event will force the execution of any
finally clause in the try
statement, allowing the generator to release the resources it
acquired.
g, (.throwtype, 〈value〉, 〈traceback〉)
The throw method will force the
generator to handle an exception when it reaches the next
yield statement. This allows a client function
to send exception events into the generator.
g, (.sendarg)
→ next value
This is a variation on the next
method; it also resumes execution after the
yield statement. The argument values will
become the return value from the yield
statement. The generator can then use these values to change it's
internal state and yield another value or raise
StopIteration.
Published under the terms of the Open Publication License