[Python-Dev] PEP 463: Exception-catching expressions

Chris Angelico rosuav at gmail.com
Sat Feb 22 04:51:57 CET 2014


On Sat, Feb 22, 2014 at 10:29 AM, Greg Ewing
<greg.ewing at canterbury.ac.nz> wrote:
> Antoine Pitrou wrote:
>
>>>    lst = [1, 2]
>>>    value = lst[2] except IndexError: "No value"
>>
>>
>> the gain in concision is counterbalanced by a loss in
>> readability,
>
>
> This version might be more readable:
>
>    value = lst[2] except "No value" if IndexError
>
> since it puts the normal and exceptional values next
> to each other, and relegates the exception type (which
> is of much less interest) to a trailing aside.

I'll expand on this in the PEP shortly, but there are two downsides to this.

1) Everywhere else in Python, "if" is followed by a boolean, and
"except" is followed by an exception list. As a boolean, IndexError is
always going to be true, which will confuse a human; and "No value"
doesn't look like a modern exception at all.

2) Order of evaluation puts the main expression first, then the
exception list, and lastly the default. Putting them in another order
in the code is confusing. With ternary if/else, this is justified, but
it's usually something to avoid.

3) Erm, among the downsides are such diverse elements... ahem. The
part after the except clause is a full expression, and could plausibly
have the if/else ternary operator. Starting with some expression, then
if, then another expression, means you have to look for an else before
you can be sure you're reading it correctly. Of course, any sane
programmer who actually puts an if/else inside an except/if should
parenthesize, but when you read someone else's code, you have to be
prepared for the more normal sort of programmer.

ChrisA


More information about the Python-Dev mailing list