|Python Language Reference Manual|
by Guido van Rossum and Fred L. Drake, Jr.
Paperback (6"x9"), 120 pages
RRP £12.95 ($19.95)
Sales of this book support the Python Software Foundation! Get a printed copy>>>
yield statement is only used when defining a generator
function, and is only used in the body of the generator function.
yield statement in a function definition is
sufficient to cause that definition to create a generator function
instead of a normal function.
When a generator function is called, it returns an iterator known as a
generator iterator, or more commonly, a generator. The body of the
generator function is executed by calling the generator's
next() method repeatedly until it raises an exception.
yield statement is executed, the state of the
generator is frozen and the value of
next()'s caller. By "frozen" we mean that all
local state is retained, including the current bindings of local
variables, the instruction pointer, and the internal evaluation stack:
enough information is saved so that the next time
invoked, the function can proceed exactly as if the
statement were just another external call.
As of Python version 2.5, the
yield statement is now
allowed in the
try clause of a
finally construct. If the generator is not resumed before
it is finalized (by reaching a zero reference count or by being garbage
collected), the generator-iterator's
close() method will be
called, allowing any pending
finally clauses to execute.
In Python 2.2, the
yield statement is only allowed
generators feature has been enabled. It will always
be enabled in Python 2.3. This
__future__ import statement can
be used to enable the feature:
from __future__ import generators
- PEP0255 Simple Generators
The proposal for adding generators and the
yieldstatement to Python.
- PEP0342 Coroutines via Enhanced Generators
The proposal that, among other generator enhancements, proposed allowing
yieldto appear inside a
|ISBN 0954161785||Python Language Reference Manual||See the print edition|