diff options
Diffstat (limited to 'Doc/reference')
-rw-r--r-- | Doc/reference/simple_stmts.rst | 31 |
1 files changed, 30 insertions, 1 deletions
diff --git a/Doc/reference/simple_stmts.rst b/Doc/reference/simple_stmts.rst index e149710..a9d534e 100644 --- a/Doc/reference/simple_stmts.rst +++ b/Doc/reference/simple_stmts.rst @@ -438,7 +438,36 @@ The :keyword:`yield` statement is only used when defining a generator function, and is only used in the body of the generator function. Using a :keyword:`yield` statement in a function definition is sufficient to cause that definition to create a generator function instead of a normal function. ->>>>>>> .merge-right.r59773 +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 :meth:`next` method repeatedly until it +raises an exception. + +When a :keyword:`yield` statement is executed, the state of the generator is +frozen and the value of :token:`expression_list` is returned to :meth:`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 :meth:`next` +is invoked, the function can proceed exactly as if the :keyword:`yield` +statement were just another external call. + +As of Python version 2.5, the :keyword:`yield` statement is now allowed in the +:keyword:`try` clause of a :keyword:`try` ... :keyword:`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 +:meth:`close` method will be called, allowing any pending :keyword:`finally` +clauses to execute. + + +.. seealso:: + + :pep:`0255` - Simple Generators + The proposal for adding generators and the :keyword:`yield` statement to Python. + + :pep:`0342` - Coroutines via Enhanced Generators + The proposal that, among other generator enhancements, proposed allowing + :keyword:`yield` to appear inside a :keyword:`try` ... :keyword:`finally` block. + .. _raise: |