[Python-Dev] PEP 340: Else clause for block statements

Guido van Rossum gvanrossum at gmail.com
Mon May 2 16:57:19 CEST 2005


[Guido, prsenting a use case]
> >   block locking(myLock, timeout=30):
> >       ...code executed with lock held...
> >   else:
> >       ...code executed if lock not acquired...

[Anders Munch]
> A file-closing block function has the same need, as does any block
> function that manages a resource, whose acquisition might fail.
> 
> A surrounding try/except doesn't quite cut it; the problem is that the
> try-clause will then also cover the suite.
> 
> Example:
> 
>     try:
>         in opening('file1') as f1:
>             ...
>             in opening('file2') as f2:
>                 ...
>     except IOError:
>         print "file1 not available, I'll try again later"

I thought of this and several other solutions overnight and didn't lik
any. Finally I realized that this use case is better covered by
letting the generator return an error value:

def opening_w_err(filename):
    try:
        f = open(filename)
    except IOError, err:
        yield None, err
    else:
        try:
            yield f, None
        finally:
            f.close()

The user can then write:

block opening_w_err(filename) as f, err:
    if f:
        ...code using f...
    else:
        ...error handling code using err...

Besides, in many cases it's totally acceptable to put a try/except
block around the entire block-statement, if the exception it catches
is specific enough (like IOError). For example:

try:
    block opening(filename) as f:
        ...code using f...
except IOError, err:
    ...error handling code using err...

So I'm more than ever in favor of keeping the block-statement simple,
i.e. without any additional clauses.

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


More information about the Python-Dev mailing list