Text of peps.python.org › pep-0340 as Styx crawled it on Nov 18, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

PEP 340 – Anonymous Block Statements | peps.python.org

PEP 340 – Anonymous Block Statements PEP 340 – Anonymous Block Statements Author : Guido van Rossum Status : Rejected Type : Standards Track Created : 27-Apr-2005 Post-History : Table of Contents Introduction Rejection Notice Motivation and Summary Use Cases Specification: the __exit__() Method Specification: the Anonymous Block Statement Specification: Generator Exit Handling Alternatives Considered and Rejected Comparison to Thunks Examples Acknowledgements References Copyright Introduction This PEP proposes a new type of compound statement which can be used for resource management purposes.

The new statement type is provisionally called the block-statement because the keyword to be used has not yet been chosen. This PEP competes with several other PEPs: PEP 288 (Generators Attributes and Exceptions; only the second part), PEP 310 (Reliable Acquisition/Release Pairs), and PEP 325 (Resource-Release Support for Generators). I should clarify that using a generator to “drive” a block statement is really a separable proposal; with just the definition of the block statement from the PEP you could implement all the examples using a class (similar to example 6, which is easily turned into a template).

But the key idea is using a generator to drive a block statement; the rest is elaboration, so I’d like to keep these two parts together. ( PEP 342 , Enhanced Iterators, was originally a part of this PEP; but the two proposals are really independent and with Steven Bethard’s help I have moved it to a separate PEP.) Rejection Notice I am rejecting this PEP in favor of PEP 343 . See the motivational section in that PEP for the reasoning behind this rejection.

GvR. Motivation and Summary (Thanks to Shane Hathaway – Hi Shane!) Good programmers move commonly used code into reusable functions. Sometimes, however, patterns arise in the structure of the functions rather than the actual sequence of statements. For example, many functions acquire a lock, execute some code specific to that function, and unconditionally release the lock. Repeating the locking code in every function that uses it is error prone and makes refactoring difficult.

Block statements provide a mechanism for encapsulating patterns of structure. Code inside the block statement runs under the control of an object called a block iterator. Simple block iterators execute code before and after the code inside the block statement. Block iterators also have the opportunity to execute the controlled code more than once (or not at all), catch exceptions, or receive data from the body of the block statement.

A convenient way to write block iterators is to write a generator ( PEP 255 ). A generator looks a lot like a Python function, but instead of returning a value immediately, generators pause their execution at “yield” statements. When a generator is used as a block iterator, the yield statement tells the Python interpreter to suspend the block iterator, execute the block statement body, and resume the block iterator when the body has executed.

The Python interpreter behaves as follows when it encounters a block statement based on a generator. First, the interpreter instantiates the generator and begins executing it. The generator does setup work appropriate to the pattern it encapsulates, such as acquiring a lock, opening a file, starting a database transaction, or starting a loop. Then the generator yields execution to the body of the block statement using a yield statement.

When the block statement body completes, raises an uncaught exception, or sends data back to the generator using a continue statement, the generator resumes. At this point, the generator can either clean up and stop or yield again, causing the block statement body to execute again. When the generator finishes, the interpreter leaves the block statement. Use Cases See the Examples section near the end. Specification: the __exit__() Method An optional new method for iterators is proposed, called __exit__() .

It takes up to three arguments which correspond to the three “arguments” to the raise-statement: type, value, and traceback. If all three arguments are None , sys.exc_info() may be consulted to provide suitable default values. Specification: the Anonymous Block Statement A new statement is proposed with the syntax: block EXPR1 as VAR1 : BLOCK1 Here, ‘block’ and ‘as’ are new keywords; EXPR1 is an arbitrary expression (but not an expression-list) and VAR1 is an arbitrary assignment target (which may be a comma-separated list).

The “as VAR1” part is optional; if omitted, the assignments to VAR1 in the translation below are omitted (but the expressions assigned are still evaluated!). The choice of the ‘block’ keyword is contentious; many alternatives have been proposed, including not to use a keyword at all (which I actually like). PEP 310 uses ‘with’ for similar semantics, but I would like to reserve that for a with-statement similar to the one found in Pascal and VB. (Though I just found that the C# designers don’t like ‘with’ [2] , and I have to agree with their reasoning.) To sidestep this issue momentarily I’m using ‘block’ until we can agree on the right keyword, if any.

Note that the ‘as’ keyword is not contentious (it will finally be elevated to proper keyword status). Note that it is up to the iterator to decide whether a block-statement represents a loop with multiple iterations; in the most common use case BLOCK1 is executed exactly once. To the parser, however, it is always a loop; break and continue return transfer to the block’s iterator (see below for details). The translation is subtly different from a for-loop: iter() is not called, so EXPR1 should already be an iterator (not just an iterable); and the iterator is guaranteed to be notified when the block-statement is left, regardless if this is due to a break, return or exception: itr = EXPR1 # The iterator ret = False # True if a return statement is active val = None # Return value, if ret == True exc = None # sys.exc_info() tuple if an exception is active while True : try : if exc : ext = getattr ( itr , "__exit__" , None ) if ext is not None : VAR1 = ext ( * exc ) # May re-raise *exc else : raise exc [ 0 ], exc [ 1 ], exc [ 2 ] else : VAR1 = itr . next () # May raise StopIteration except StopIteration : if ret : return val break try : ret = False val = exc = None BLOCK1 except : exc = sys . exc_info () (However, the variables ‘itr’ etc. are not user-visible and the built-in names used cannot be overridden by the user.) Inside BLOCK1 , the following special translations apply: “break” is always legal; it is translated into: exc = ( StopIteration , None , None ) continue “return EXPR3” is only legal when the block-statement is contained in a function definition; it is translated into: exc = ( StopIteration , None , None ) ret = True val = EXPR3 continue The net effect is that break and return behave much the same as if the block-statement were a for-loop, except that the iterator gets a chance at resource cleanup before the block-statement is left, through the optional __exit__() method.

The iterator also gets a chance if the block-statement is left through raising an exception. If the iterator doesn’t have an __exit__() method, there is no difference with a for-loop (except that a for-loop calls iter() on EXPR1 ). Note that a yield-statement in a block-statement is not treated differently. It suspends the function containing the block without notifying the block’s iterator. The block’s iterator is entirely unaware of this yield, since the local control flow doesn’t actually leave the block.

In other words, it is not like a break or return statement. When the loop that was resumed by the yield calls next() , the block is resumed right after the yield. (See example 7 below.) The generator finalization semantics described below guarantee (within the limitations of all finalization semantics

The rest of this page is on the live site.