[Python-Dev] Re: anonymous blocks

Brett C. bac at OCF.Berkeley.EDU
Wed Apr 27 22:20:34 CEST 2005

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

I am at least +0 on all of this now, with a slow warming up to +1 (but then it
might just be the cold talking  =).

I still prefer the idea of arguments to __next__() be raised if they are
exceptions and otherwise just be returned through the yield expression.  But I
do realize this is easily solved with a helper function now::

 def raise_or_yield(val):
     """Return the argument if not an exception, otherwise raise it.

     Meant to have a yield expression as an argument.  Worries about
     Iteration subclasses are invalid since they will have been handled by the
     __next__() method on the generator already.

     if isinstance(val, Exception):
        raise val
        return val

My objections that I had earlier to 'continue' and 'break' being somewhat
magical in block statements has subsided.  It all seems reasonable now within
the context of a block statement.

And while the thought is in my head, I think block statements should be viewed
less as a tweaked version of a 'for' loop and more as an extension to
generators that happens to be very handy for resource management (while
allowing iterators to come over and play on the new swing set as well).  I
think if you take that view then the argument that they are too similar to
'for' loops loses some luster (although I doubt Nick is going to be buy this  =) .

Basically block statements are providing a simplified, syntactically supported
way to control a generator externally from itself (or at least this is the
impression I am getting).  I just had a flash of worry about how this would
work in terms of abstractions of things to functions with block statements in
them, but then I realized you just push more code into the generator and handle
it there with the block statement just driving the generator.  Seems like this
might provide that last key piece for generators to finally provide cool flow
control that we all know they are capable of but just required extra work


More information about the Python-Dev mailing list