On 2/27/2014 4:57 AM, Nick Coghlan wrote:
The way I get the colon in the proposed syntax to make sense to my brain is to view it as being more like the colon in a dictionary key:value pair than it is like the one that introduces a suite or the body of a lambda expression:
(lst[2] except {IndexError: "No value"})
The analogy isn't exact (since exception handling is isinstance() based rather than equality based), but I think it gives the right general flavour in terms of the intended meaning of the colon in this construct. The analogy could likely be encouraged and strengthened by changing the parentheses requirements to make this read more like a binary except expression with a parenthesised RHS rather than a ternary expression:
lst[2] except (IndexError: "No value")
Catching multiple errors would involve a parenthesised tuple as the "key":
f() except ((TypeError, AttributeError): "No value")
The deferred "multiple except clauses" part of the PEP could also change to be more dict display like:
value = expr except ( Exception1: default1, Exception2: default2, Exception3: default3, )
Writing out those examples, I actually like that version (where the parentheses are still mandatory, but the left paren is after the except keyword rather than before the first expression) better than the one currently in the PEP. It also avoids the weirdly unbalanced look of the variant that had the left paren*before* the except keyword. The main downside I see is that the exception handling definition syntax would only be permitted in that specific location, but still look a lot like an ordinary parenthesised expression.
Cheers, Nick. +1
f() except ((TypeError, AttributeError): "No value") is a nice extension to the idea of value = expr except ( Exception1: default1, Exception2: default2, Exception3: default3, ) Which I've liked since I first saw it, as it neatly solves handling multiple except clauses.