[Python-ideas] except expression

Andrew Barnert abarnert at yahoo.com
Tue Feb 18 08:33:34 CET 2014


On Feb 17, 2014, at 22:37, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:

> Rob Cliffe wrote:
>> On 17/02/2014 22:26, Greg Ewing wrote:
>>>   menu.remove(mint) except ValueError: pass
>> I'm starting to like it,  although it introduces an inconsistency between expressions whose values are used and those whose values are not used.
> 
> If it helps, you could think of this form of the syntax
> as a statement rather than an expression.

That helps a lot, in that it explains exactly what's wrong with the idea.

The except expression is useful because it lets you handle exceptions in any expression context--a function argument, whatever. Code that would otherwise be clunky to write becomes simple. The fact that it also lets you avoid a newline or two is not the point, and is barely worth mentioning as an added bonus.

Adding pass to the except expression does not allow any code to become simpler. The _only_ thing it does is allow you to avoid a newline. And it doesn't even do _that_:

> It's an
> abbreviation for
> 
>   try:
>      menu.remove(mint)
>   except ValueError:
>      pass
> 
> which you wouldn't otherwise be able to write on one line.

Sure you would:

    menu.remove(mint) except ValueError: None

Exactly as short as the "pass" version, and without requiring the user or the compiler (or the linter, font-lock mode, etc.) to go through the hurdles of realizing that this is happening at the top level of an expression statement, rather than just in any expression, and therefore the value is guaranteed ignored (which isn't actually even true, given things like _ at the interactive interpreter, but we have to _pretend_ it is to even make sense of the idea), and therefore we use different syntax with a pass keyword in place of a value.

OK, it does require one more keystroke to capitalize the N, but if that bothers you, write it this way:

    menu.remove(mint) except ValueError: 0



More information about the Python-ideas mailing list