[Python-Dev] Re: anonymous blocks

Guido van Rossum gvanrossum at gmail.com
Wed Apr 27 19:42:04 CEST 2005


> 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.

Ouch. Another bug in the PEP. It was late. ;-)

The "finally:" should have been "except StopIteration:" I've updated
the PEP online.

> 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

No, this would just propagate the StopIteration when next() raises it.
StopIteration is not caught implicitly except around the next() call
made by the for-loop control code.

-- 
--Guido van Rossum (home page: http://www.python.org/~guido/)


More information about the Python-Dev mailing list