[Python-ideas] except expression

Chris Angelico rosuav at gmail.com
Thu Feb 13 12:48:08 CET 2014


On Thu, Feb 13, 2014 at 10:25 PM, spir <denis.spir at gmail.com> wrote:
> I don't see any issue with:
>     phone = addressbook[name] except "Unknown" if KeyError
>     phone = addressbook[name] except "Unknown" if KeyError as e
> It is similar in syntax and meaning with if-expressions, with the first
> keyword 'except' obviously making all the difference we need.

So the keyword 'if' would come up in two different expression contexts:

value if cond else othervalue

value except othervalue if cond

In each case, the condition (which in the latter is an exception type,
while in the former it's a boolean) follows the word 'if', just as it
does in the statement form. That's reasonably elegant. Problem is,
that loses the elegance of matching the statement form of 'except',
which has the exception type following the word 'except'.

I'd kinda like to see it worded as "if except", but then it needs
something else to separate the exception(s) from the value. It could
actually be done just like the if/else form, except (pun intended)
that that overemphasizes the exceptional case:

phone = "Unknown" if except KeyError else addressbook[name]

In terms of argument order, I'm looking for:

phone = addressbook[name] unless except KeyError as e then "Unknown"

but neither 'unless' nor 'then' is currently a keyword.

> [By the way, this shows that:
>         x = b if cond else a
> should really be:
>         x = a else b if cond
> The difference being that the standard case is expressed first, the
> exceptional one being then introduced as an special variant.]

My example tends to agree with you... but my example is using "if" to
introduce the abnormal case, whereas it's common to spell a block if
the other way:

if normal-case:
    code code code
else:
    abnormal code

C's ternary operator puts the expressions in the order "condition,
if_true, if_false". Python's puts them "if_true, condition, if_false".
You're proposing "if_false, if_true, condition". We're half way to
covering all the permutations!

ChrisA


More information about the Python-ideas mailing list