[Python-ideas] except expression

MRAB python at mrabarnett.plus.com
Wed Feb 19 03:50:41 CET 2014


On 2014-02-19 00:58, Jan Kaliszewski wrote:
> 18.02.2014 16:56, Paul Moore wrote:
>
>> On 18 February 2014 15:05, Chris Angelico <rosuav at gmail.com> wrote:
>>>> Well, yes and no. There are only 2 out of the 10 syntaxes
>>>> originally
>>>> proposed in the PEP at the start of this thread that use a colon.
>>>> I've
>>>> already pointed out that I don't like a colon, so assume I said
>>>> "except return 0" if you must :-)
>>>
>>> Whether it's a colon or another keyword, _something_ is necessary in
>>> there, if it's permissible to specify an exception type:
>>>
>>> sum(x[3] except IndexError 0 for x in list_of_tuples)
>>> sum(x[3] except 0 for x in list_of_tuples)
>>>
>>> How would you parse each of those, without a separator?
>>
>> With "return" as a separator. I said that above. Was I not clear?
>
> IMHO it would be an abuse of the keyword. "return" is very strong
> signal to programmers eyes: "here we exit the body of the function"
> (and the function must be defined in the statement-based way: by def,
> not by lambda; return is not used in lambda so in an except
> expression it would even more alien and out of place).
>
>>> One option might be to have a separator that's present only when the
>>> exception type is listed. For instance:
>>>
>>> sum(x[3] except(IndexError) 0 for x in list_of_tuples)
>>> sum(x[3] except 0 for x in list_of_tuples)
>>>
>>> Does that sort of thing have enough support to be added to the PEP?
>>> I'm not sure it gives us anything over the colon notation, which has
>>> the benefit of being consistent with the statement form (and is
>>> stylistically similar to lambda, so it's not grossly inappropriate
>>> to
>>> an expression context)
>>
>> I remain less than happy with the colon notation, although I will
>> concede that the basic
>>
>>     x[3] except IndexError: 0
>>
>> form is not horrible - it just becomes horrible very, very fast when
>> people try to do anything more complicated than that.
> [snip]
>
> IMHO it'll not become horible if some parens are added...
>
> ...either after 'except' (my favorite variant):
>
>       x[3] except (IndexError: 0)
>
>       sum(x[3] except (IndexError: 0)
>           for x in list_of_tuples)
>
-1

That would preclude a tuple of exceptions.

> ...or before 'except':
>
>       x[3] (except IndexError: 0)
>
>       sum(x[3] (except IndexError: 0)
>           for x in list_of_tuples)
>
-1

That looks like a call.

> ...or just enclosing the whole expression:
>
>       (x[3] except IndexError: 0)
>
>       sum((x[3] except IndexError: 0)
>           for x in list_of_tuples)
>
No complaints there!



More information about the Python-ideas mailing list