[Python-ideas] except expression

Chris Angelico rosuav at gmail.com
Wed Feb 19 09:39:37 CET 2014


On Wed, Feb 19, 2014 at 7:23 PM, Bruce Leban <bruce at leapyear.org> wrote:
> On Tue, Feb 18, 2014 at 11:06 PM, Chris Angelico <rosuav at gmail.com> wrote:
>>
>> However, I'm removing two parts of the proposal: ... chaining of
>>
>> excepts (use parens, "(expr except Exception1: default1) except
>> Exception2: default2").
>
>
> There are two problems with trying to leave this out.
>
> First, you say "use parens" but no use of parenthesis can have the same
> effect. The alternative you give:
>     (expr except E1: default1) except E2: default2
> is not the same as the chained form. This catches E2 in both the evaluation
> of E1 and the evaluation of default1 while the chained form catches both
> exceptions only in the evaluation of E1. And putting parens anywhere else
> doesn't do it either.

Correct.

> Second, isn't an except expression like any other expression which can be
> used anywhere an expression can be? So that means that writing something
> that looks like a chained expression without parenthesis will be a valid
> expression and will have to have some interpretation (depending on whether
> except is left associative or right associative.

Not quite; it could be made a SyntaxError to abut two except
expressions without parens. Failing that, the without-parens form
would always mean nesting (or what Steven calls chaining), and a
future development that puts a single try with multiple excepts would
have to be done with commas.

But there's still one big question: What use-case have you for the
multi-catch form? (Maybe call it "continued"? "extended"??) I went
through the standard library and found pretty much nothing that even
tripped my checks, and those were sufficiently borderline that they
could just be left as statements.

Do you have a good-sized Python codebase that you could either point
me to, or run my little finder script on? I want to see more code that
would benefit from this, and to see if there are any current use-cases
that need multiple except clauses. I'd be looking for something like
this:

try:
    foo = expression
except SomeException:
    foo = another_expression
except SomeOtherException:
    foo = some_other_expression

Any real-world examples would be appreciated. Even if that
sub-proposal doesn't get accepted, it'd still be improved by examples.

ChrisA


More information about the Python-ideas mailing list