@@ -15,6 +15,7 @@ \chapter{Simple statements \label{simple}}
1515 | \token {del_stmt}
1616 | \token {print_stmt}
1717 | \token {return_stmt}
18+ | \token {yield_stmt}
1819 | \token {raise_stmt}
1920 | \token {break_stmt}
2021 | \token {continue_stmt}
@@ -436,6 +437,57 @@ \section{The \keyword{return} statement \label{return}}
436437before really leaving the function.
437438\kwindex {finally}
438439
440+ In a generator function, the \keyword {return} statement is not allowed
441+ to include an \grammartoken {expression_list}. In that context, a bare
442+ \keyword {return} indicates that the generator is done and will cause
443+ \exception {StopIteration} to be raised.
444+
445+
446+ \section {The \keyword {yield} statement \label {yield } }
447+ \stindex {yield}
448+
449+ \begin {productionlist }
450+ \production {yield_stmt}
451+ {"yield" \token {expression_list}}
452+ \end {productionlist }
453+
454+ \index {generator!function}
455+ \index {generator!iterator}
456+ \index {function!generator}
457+ \exindex {StopIteration}
458+
459+ The \keyword {yield} statement is only used when defining a generator
460+ function, and is only used in the body of the generator function.
461+ Using a \keyword {yield} statement in a function definition is
462+ sufficient to cause that definition to create a generator function
463+ instead of a normal function.
464+
465+ When a generator function is called, it returns an iterator known as a
466+ generator iterator, or more commonly, a generator. The body of the
467+ generator function is executed by calling the generator's
468+ \method {next()} method repeatedly until it raises an exception.
469+
470+ When a \keyword {yield} statement is executed, the state of the
471+ generator is frozen and the value of \grammartoken {expression_list} is
472+ returned to \method {next()}'s caller. By `` frozen'' we mean that all
473+ local state is retained, including the current bindings of local
474+ variables, the instruction pointer, and the internal evaluation stack:
475+ enough information is saved so that the next time \method {next()} is
476+ invoked, the function can proceed exactly as if the \keyword {yield}
477+ statement were just another external call.
478+
479+ One restriction in the use of the \keyword {yield} statement is is that
480+ is is not allowed in the try clause of a \keyword {try}
481+ ...\ \keyword {finally} construct. The difficulty is that there's no
482+ guarantee the generator will ever be resumed, hence no guarantee that
483+ the \keyword {finally} block will ever get executed.
484+
485+ \begin {seealso }
486+ \seepep {0255}{Simple Generators}
487+ {The proposal for adding generators and the \keyword {yield}
488+ statement to Python.}
489+ \end {seealso }
490+
439491
440492\section {The \keyword {raise} statement \label {raise } }
441493\stindex {raise}
0 commit comments