[Python-Dev] Re: anonymous blocks

Tim Delaney tcdelaney at optusnet.com.au
Thu Apr 28 00:34:59 CEST 2005

Guido van Rossum wrote:

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


A minor sticking point - I don't like that the generator has to re-raise any 
``StopIteration`` passed in. Would it be possible to have the semantics be:

    If a generator is resumed with ``StopIteration``, the exception is 
    at the resumption point (and stored for later use). When the generator
    exits normally (i.e. ``return`` or falls off the end) it re-raises the
    stored exception (if any) or raises a new ``StopIteration`` exception.

So a generator would become effectively::

        stopexc = None
        exc = None
        if exc is not None:
            raise exc

        if stopexc is not None:
            raise stopexc

        raise StopIteration

where within BLOCK1:

    ``raise <exception>`` is equivalent to::

        exc = <exception>

    The start of an ``except`` clause sets ``exc`` to None (if the clause is
    executed of course).

    Calling ``__next__(exception)`` with ``StopIteration`` is equivalent 

        stopexc = exception
        (raise exception at resumption point)

    Calling ``__next__(exception)`` with ``ContinueIteration`` is equivalent 

        (resume exception with exception.value)

    Calling ``__next__(exception)__`` with any other value just raises that 
    at the resumption point - this allows for calling with arbitrary 

Also, within a for-loop or block-statement, we could have ``raise 
<exception>`` be equivalent to::

    arg = <exception>

This also takes care of Brett's concern about distinguishing between 
exceptions and values passed to the generator. Anything except StopIteration 
or ContinueIteration will be presumed to be an exception and will be raised. 
Anything passed via ContinueIteration is a value.

Tim Delaney 

More information about the Python-Dev mailing list