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

Glenn Linderman v+python at g.nevcal.com
Thu Feb 27 20:36:01 CET 2014

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.

     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.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20140227/988a41a5/attachment.html>

More information about the Python-Dev mailing list