Add section explaining that yield *isn't* special wrt try/except/finally.

This commit is contained in:
Tim Peters 2001-06-20 20:32:56 +00:00
parent 195afdf22f
commit db019e19e7
1 changed files with 34 additions and 0 deletions

View File

@ -199,6 +199,40 @@ Generators and Exception Propagation
>>>
Yield and Try/Except/Finally
While "yield" is a control-flow statement, and in most respects acts
like a "return" statement from the caller's point of view, within a
generator it acts more like a callback function. In particular, it has
no special semantics with respect to try/except/finally. This is best
illustrated by a contrived example; the primary lesson to take from
this is that using yield in a finally block is a dubious idea!
>>> def g():
... try:
... yield 1
... 1/0 # raises exception
... yield 2 # we never get here
... finally:
... yield 3 # yields, and we raise the exception *next* time
... yield 4 # we never get here
>>> k = g()
>>> k.next()
1
>>> k.next()
3
>>> k.next() # as if "yield 3" were a callback, exception raised now
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 4, in g
ZeroDivisionError: integer division or modulo by zero
>>> k.next() # unhandled exception terminated the generator
Traceback (most recent call last):
File "<stdin>", line 1, in ?
StopIteration
>>>
Example
# A binary tree class.