[Python-ideas] except expression

Yury Selivanov yselivanov.ml at gmail.com
Thu Feb 20 02:11:30 CET 2014


On 2/19/2014, 7:56 PM, Chris Angelico wrote:
> On Thu, Feb 20, 2014 at 11:22 AM, Yury Selivanov
> <yselivanov.ml at gmail.com> wrote:
>> If we add new 'raises' keyword, then we can have the following
>> new syntax:
> Cost of adding a keyword is based on its usage. Searching the standard
> library for 'raises' comes up blank; same goes for 'then', though both
> 'use' and 'when' do come up (once and twelve times, respectively). I
> think it reasonably unlikely that 'raises' will be a problem. However,
> it's very similar to an existing keyword. The English form sounds a
> little archaic, but plausible: "Do this if spam raise something".
>
>> # set 'value' to 42 if len(a) < 10
>> # or else, return a[10]
>> value = 42 if a[10] raises IndexError
> (Minor point: That should be 42 if len(a) <= 10.)
>
>> # set 'value' to 42 if len(a) < 10
>> # or else, return 'spam'
>> value = 42 if a[10] raises IndexError else 'spam'
> Have you a use-case for this? It completely ignores the original
> expression value.

Something like
    result = 'failed' if command() raises else 'ok'
>
>> # same as above but if a[10] raises anything
>> value = 42 if a[10] raises
> I'm giving this an immediate common-law rejection, as the bare-except
> sub-proposal has already been rejected.

Since it is a new keyword, we can document that it
can intercept only Exceptions, not BaseExceptions.
>
>> # another example
>> foo(None if dct['key'] raises)
> And what if it doesn't? Reads nicely for the exceptional case.
> Presumably it's the value of dct['key'] if it doesn't raise, but
> that's not obvious from how it reads.
Without this you would need to write:
    foo(None if dct['key'] raises else dct[key])

Which is code duplication and a performance impact,
since we'll have to evaluate expression twice.
>> This syntax doesn't provide:
>> - finally statement replacement;
>> - handling multiple exceptions;
>> - rerising exception;
>> which I think is a good thing. No need to complicate this
>> syntax.
> I'm fine with those absences.
>
>> Pros:
>> - easy to read (like English or pseudocode)
>> - looks like existing 'expr if expr else expr' syntax
>>
>> Cons:
>> - adds a new keyword
> That's not a killer, by any means.
>
> My main objection here is that it reads backwards.
Yes, that's understandable.

Although, as you yourself noted, Python has
'expr if expr else expr' already. Yes, it is a bit awkward,
but lots of people (including me) find it very readable and
easy to understand.

Same with my proposal. If follows the already established
syntax and reads nicely.

Could you please add to the PEP (in other proposals section?)

Yury




More information about the Python-ideas mailing list