On 2014-02-15 23:46, Chris Angelico wrote:
On Sun, Feb 16, 2014 at 10:17 AM, Greg Ewing
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)
You'll also need to note that: ((expr except Exception1: default1) except Exception2: default2) is not the same as: (expr except Exception1: default1 except Exception2: default2) The first will also catch Exception2 if default1 raises it, whereas the second will catch Exception2 only if expr raises it and it hasn't been caught by the preceding 'except'.
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@?