[Python-Dev] Re: anonymous blocks

Josiah Carlson jcarlson at uci.edu
Wed Apr 27 18:44:12 CEST 2005


Guido van Rossum <gvanrossum at gmail.com> wrote:
> 
> I've written a PEP about this topic. It's PEP 340: Anonymous Block
> Statements (http://python.org/peps/pep-0340.html).
> 
> Some highlights:
> 
> - temporarily sidestepping the syntax by proposing 'block' instead of 'with'
> - __next__() argument simplified to StopIteration or ContinueIteration instance
> - use "continue EXPR" to pass a value to the generator
> - generator exception handling explained

Your code for the translation of a standard for loop is flawed.  From
the PEP:

        for VAR1 in EXPR1:
            BLOCK1
        else:
            BLOCK2

    will be translated as follows:

        itr = iter(EXPR1)
        arg = None
        while True:
            try:
                VAR1 = next(itr, arg)
            finally:
                break
            arg = None
            BLOCK1
        else:
            BLOCK2


Note that in the translated version, BLOCK2 can only ever execute if
next raises a StopIteration in the call, and BLOCK1 will never be
executed because of the 'break' in the finally clause.

Unless it is too early for me, I believe what you wanted is...

        itr = iter(EXPR1)
        arg = None
        while True:
            VAR1 = next(itr, arg)
            arg = None
            BLOCK1
        else:
            BLOCK2

 - Josiah



More information about the Python-Dev mailing list