[Python-checkins] CVS: python/nondist/peps pep-0255.txt,1.7,1.8
Tim Peters
tim_one@users.sourceforge.net
Wed, 20 Jun 2001 13:32:59 -0700
Update of /cvsroot/python/python/nondist/peps
In directory usw-pr-cvs1:/tmp/cvs-serv20081/peps
Modified Files:
pep-0255.txt
Log Message:
Add section explaining that yield *isn't* special wrt try/except/finally.
Index: pep-0255.txt
===================================================================
RCS file: /cvsroot/python/python/nondist/peps/pep-0255.txt,v
retrieving revision 1.7
retrieving revision 1.8
diff -C2 -r1.7 -r1.8
*** pep-0255.txt 2001/06/20 19:08:20 1.7
--- pep-0255.txt 2001/06/20 20:32:56 1.8
***************
*** 200,203 ****
--- 200,237 ----
+ 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