[Python-ideas] except expression
Chris Angelico
rosuav at gmail.com
Sun Feb 16 00:46:15 CET 2014
On Sun, Feb 16, 2014 at 10:17 AM, Greg Ewing
<greg.ewing at canterbury.ac.nz> wrote:
>> This does look a tiny bit like a function call, especially if you delete
>> the space between the leading expression and the opening bracket:
>>
>> # ugly, don't do this
>> things[i](except IndexError: 42)
>
>
> Yes, that's why I'm leaning towards the paren-less version.
I'm not liking the parenthesized version here, because the 'except'
expression has to know how much of the preceding expression to modify.
With a function call:
expression(args)
the expression is fully evaluated first, and then whatever it returns
gets called; with the except expression, a try block has to be set up
somewhere. This is more similar to if-else than to a function call, in
that the expression before the 'if' isn't evaluated until the
condition has been tested.
Parens could go around the whole thing:
(thing[i] except IndexError: 42)
(1/x if x else "Div by 0")
but not around the except clause:
thing[i] (except IndexError: 42) # Nope
1/x (if x else "Div by 0") # Nope
Incidentally, I'm looking at this being able to chain quite nicely:
((expr except Exception1: default1) except Exception2: default2)
Ideally the peephole optimizer could set up a single try/except
structure for both, but syntactically, I'm seeing this as the way the
operator associates.
I've mailed the first-draft PEP to peps@; is it appropriate to post it
here as well, or should I wait to hear back from peps@?
ChrisA
More information about the Python-ideas
mailing list