diff --git a/pep-0340.txt b/pep-0340.txt index 93050b21c..37533da3d 100644 --- a/pep-0340.txt +++ b/pep-0340.txt @@ -122,7 +122,7 @@ Specification: a Change to the 'for' Loop will be translated as follows: itr = iter(EXPR1) - arg = None + arg = None # Set by "continue EXPR2", see below brk = False while True: try: @@ -496,7 +496,7 @@ Examples block locking(myLock): # Code here executes with myLock held. The lock is # guaranteed to be released when the block is left (even - # if by an uncaught exception). + # if via return or by an uncaught exception). 2. A template for opening a file that ensures the file is closed when the block is left: @@ -557,6 +557,11 @@ Examples for line in f: print line.rstrip() + (If this example confuses you, consider that it is equivalent + to using a for-loop with a yield in its body in a regular + generator which is invoking another iterator or generator + recursively; see for example the source code for os.walk().) + 6. It is possible to write a regular iterator with the semantics of example 1: @@ -581,6 +586,10 @@ Examples self.lock.release() raise type, value, traceback + (This example is easily modified to implement the other + examples; it shows how much simpler generators are for the same + purpose.) + 7. Redirect stdout temporarily: def redirecting_stdout(new_stdout): @@ -597,6 +606,30 @@ Examples block redirecting_stdout(f): print "Hello world" + 8. A variant on opening() that also returns an error condition: + + def opening_w_error(filename, mode="r"): + try: + f = open(filename, mode) + except IOError, err: + yield None, err + else: + try: + yield f, None + finally: + f.close() + + Used as follows: + + block opening_w_error("/etc/passwd", "a") as f, err: + if err: + print "IOError:", err + else: + f.write("guido::0:0::/:/bin/sh\n") + + 9. More examples are needed: showing "continue EXPR", and the use + of continue, break and return in a block-statement. + Acknowledgements In no useful order: Alex Martelli, Barry Warsaw, Bob Ippolito,