[Python-Dev] Re: anonymous blocks

Duncan Booth duncan.booth at suttoncourtenay.org.uk
Wed Apr 27 14:22:20 CEST 2005


Jim Fulton <jim at zope.com> wrote in news:426F7A8F.8090109 at zope.com:

> Guido van Rossum wrote:
>> I've written a PEP about this topic. It's PEP 340: Anonymous Block
>> Statements (http://python.org/peps/pep-0340.html).
>> 
> Some observations:
> 
> 1. It looks to me like a bare return or a return with an EXPR3 that
> happens 
>     to evaluate to None inside a block simply exits the block, rather
>     than exiting a surrounding function. Did I miss something, or is
>     this a bug?
> 

No, the return sets a flag and raises StopIteration which should make the 
iterator also raise StopIteration at which point the real return happens.

If the iterator fails to re-raise the StopIteration exception (the spec 
only says it should, not that it must) I think the return would be ignored 
but a subsquent exception would then get converted into a return value. I 
think the flag needs reset to avoid this case.

Also, I wonder whether other exceptions from next() shouldn't be handled a 
bit differently. If BLOCK1 throws an exception, and this causes the 
iterator to also throw an exception then one exception will be lost. I 
think it would be better to propogate the original exception rather than 
the second exception.

So something like (added lines to handle both of the above):

        itr = EXPR1
        exc = arg = None
        ret = False
        while True:
            try:
                VAR1 = next(itr, arg)
            except StopIteration:
                if exc is not None:
                    if ret:
                        return exc
                    else:
                        raise exc   # XXX See below
                break
+           except:
+               if ret or exc is None:
+                   raise
+               raise exc # XXX See below
+           ret = False
            try:
                exc = arg = None
                BLOCK1
            except Exception, exc:
                arg = StopIteration()


More information about the Python-Dev mailing list