[Python-ideas] except expression

Chris Angelico rosuav at gmail.com
Thu Feb 20 05:41:32 CET 2014


On Thu, Feb 20, 2014 at 3:23 PM, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> Chris Angelico wrote:
>>
>> On Thu, Feb 20, 2014 at 2:13 PM, Greg Ewing <greg.ewing at canterbury.ac.nz>
>> wrote:
>>
>>>   things[i] except IndexError if None
>>>
>>> and you have even half your wits about you, then you'll
>>> notice that something doesn't make sense when you get to
>>> the 'if'.
>>
>>
>> Actually, you have to keep going to see if you hit an 'else', because
>> "IndexError if None else something_else" is the same as
>> "something_else".
>
>
> For sanity, parentheses should probably be required
> for that interpretation:
>
>    things[i] except (value if cond else other_value) if IndexError

Unless you require them all the time, parsing's going to have to go
all the way to the end of the expression before being sure of its
interpretation. I'm not sure that's a good thing. Again, it may or may
not be a problem for a computer lexer, but a human would have to
remember to look for the else, just in case.

Of course, I don't often expect people to be often writing stuff like
this, but it is technically legal:

things[i] except None if IndexError if issubclass(things, list) else KeyError

Not to mention that this case is better handled by catching
LookupError - but not everyone knows about that. (The normal rule
against catching more than you expect isn't likely to be a problem
here. But I could imagine someone specifically avoiding LookupError in
case the other sort of error gets thrown somehow.) Yes, this should be
parenthesized; but operator precedence rules mean that this must have
one of two meanings:

(things[i] except None if IndexError) if issubclass(things, list) else KeyError
things[i] except None if (IndexError if issubclass(things, list) else KeyError)

Would you know, without looking up a precedence table, which this is?
It's clear which one the programmer intended, but would you know
whether the parser treats it the same way? Yet there must be an order
to them.

ChrisA


More information about the Python-ideas mailing list