diff --git a/pep-0255.txt b/pep-0255.txt index ae94aacb2..246c383f9 100644 --- a/pep-0255.txt +++ b/pep-0255.txt @@ -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 "", line 1, in ? + File "", line 4, in g + ZeroDivisionError: integer division or modulo by zero + >>> k.next() # unhandled exception terminated the generator + Traceback (most recent call last): + File "", line 1, in ? + StopIteration + >>> + + Example # A binary tree class.