[Python-ideas] "try with" syntactic sugar

Arnaud Delobelle arnodel at googlemail.com
Fri Feb 27 11:49:24 CET 2009


2009/2/26 Daniel Stutzbach <daniel at stutzbachenterprises.com>:
> Around two-thirds of the time, whenever I use the wonderful new "with"
> construct, it's enclosed in a "try-except" block, like this:
>
> try:
>    with something as f:
>         many lines of code
> except some_error:
>     handle error
>
> The "with" statement is great, but it results in the bulk of the code being
> indented twice.  I'd like to propose a little syntactic sugar, the "try
> with":
>
> try with something as f:
>     many lines of code
> except some_error:
>     handle error
>
> It saves one line of vertical space, and gets rid of an indentation level
> for the bulk of the code that rests within the "with" statement.  Thoughts?

Every compound statement could be made into an implicit try, i.e.

    <compound statement>:
        <suite1>
    except:
        <suite2>

would mean:

    try:
        <compound statement>:
            <suite1>
    except:
        <suite2>

So you could write:

    with something as f:
        many lines of code
    except some_error:
        handle error

-- 
Arnaud



More information about the Python-ideas mailing list