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

Rob Cliffe rob.cliffe at btinternet.com
Mon Feb 24 21:52:19 CET 2014


On 21/02/2014 23:36, Ethan Furman wrote:
> On 02/21/2014 02:26 PM, Eric V. Smith wrote:
>> On 2/21/2014 5:06 PM, Greg Ewing wrote:
>>>> On 21 February 2014 13:15, Chris Angelico wrote:
>>>>
>>>>> Generator expressions require parentheses, unless they would be
>>>>> strictly redundant.  Ambiguities with except expressions could be
>>>>> resolved in the same way, forcing nested except-in-except trees to be
>>>>> correctly parenthesized
>
> There would be no ambiguity if only nested excepts are allowed. If one 
> wants to catch multiple exceptions from one expression, /and do 
> something different for each one/, use the statement form as it's 
> going to be clearer.  For example:
>
>    try:
>        value = 1/x
>    except ZeroDivisionError:
>        try:
>            value = 1/default['denominator']
>        except KeyError:
>            value = NaN
>
> is much cleaner as:
>
>    value = 1/x except ZeroDivisionError: 1/default['denominator'] 
> except KeyError: NaN
>
> However, this:
>
>    try:
>       result = Parse(some_stuff)
>    except MissingOperator:
>       result = ...
>    except InvalidOperand:
>       result = ...
>    except SomethingElse:
>       result = ...
>
> would not benefit from being condensed into a single expression
>
> -- 
> ~Ethan~
Funny, my feeling was exactly the reverse. :-)
Probably because the latter seems to me to be a more natural thing to 
want to do (I find it easier to imagine use cases for it).
And also because there is no way of getting exactly the same effect with 
a parenthesized except-expression:
     (expr except ValueError: ValueErrrorMessage") except 
NameError:NameErrorMessage # doesn't quite do what I want
(here if expr raises a ValueError, evaluating ValueErrrorMessage which 
is mis-spelt will raise a NameError which will be misleadingly caught).
But I guess the truth is that any except-expression which gets too long 
and complicated should be written some other way.


More information about the Python-Dev mailing list