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

Chris Angelico rosuav at gmail.com
Sat Feb 22 05:01:46 CET 2014

On Sat, Feb 22, 2014 at 12:55 PM, Greg Ewing
<greg.ewing at canterbury.ac.nz> wrote:
> Steven D'Aprano wrote:
>>     result = computation(
>>                  int(arg) except ValueError: abort("Invalid int")
>>                  )
>> Actually, not quite so nice as I first thought, since you're relying on
>> the side-effects of abort() rather than returning a value.
> Yeah, while I was writing that I wondered whether
> you should be allowed to write
>    int(arg) except ValueError: raise UserError("Invalid int")
> That looks heretical, because 'raise' can't in any
> way be interpreted as a value-returning expression.
> But you can achieve the same result using a function
> that always raises and exception, so forbidding it
> on those grounds would be pointless.

def throw(exc):
    raise exc

int(arg) except ValueError: throw(UserError("Invalid int"))

Tiny helper function and then it doesn't need any special syntax. It's
not so much that PEP 463 forbids this, as that it doesn't explicitly
permit it. The 'default' part of the syntax is an expression, raise is
not an expression, ergo it's not permitted. But if you think this is
sufficiently common (translate an exception on the way through), show
some code and justify its addition - or just write up a separate
proposal for "raise X" to become an expression, same as "yield X" is.


More information about the Python-Dev mailing list