[Python-Dev] PEP 340: Breaking out.

Ka-Ping Yee python-dev at zesty.ca
Thu May 5 08:59:42 CEST 2005


On Thu, 5 May 2005, Delaney, Timothy C (Timothy) wrote:
> Aahz wrote:
> > My standard workaround is using exceptions, but I'm not sure how that
> > interacts with a block:
> >
> >     try:
> >         for name in filenames:
> >             with opened(name) as f:
> >                 if f.read(2) == 0xFEB0:
> >                     raise Found
> >     except Found:
> >         pass
>
> For any sane block iterator, it will work as expected. However, an evil
> block iterator could suppress the `Found` exception.

I was thinking about more use cases for the block statement,
and one of the ideas was an exception-logging block:

    def logged_exceptions(file):
        try:
            yield
        except Exception, value:
            file.write(repr(value) + '\n')

    block logged_exceptions(file):
        do stuff
        do stuff
        do stuff

...but then i wasn't sure whether this was supposed to be
possible in the proposed scheme.  Currently, generators do not
catch exceptions raised in the code that they yield values to,
because the target of the yield is in a higher stack frame.

This makes sense from a language design perspective, since
there is no try...finally construct lexically wrapping the thing
that raises the exception.  In current Python, for example,
this says 'caught outside generator':

    def spam_generator():
        try:
            yield 'spam'
        except ValueError, value:
            print 'caught inside generator'

    try:
        g = spam_generator()
        i = g.next()
        raise ValueError(5)
    except ValueError, value:
        print 'caught outside generator'

But now i'm confused.  Tim's words above seem to suggest that
the interior generator could actually catch exceptions raised
outside, by whatever is on the other end of the yield.

So, could a block statement really catch that exception inside?
I think it might be too confusing if it were possible.


-- ?!ng


More information about the Python-Dev mailing list