For review: PEP 308 - If-then-else expression

James Kew james.kew at btinternet.com
Fri Feb 7 17:55:05 EST 2003


Guido van Rossum wrote:
>         <expression1> if <condition> else <expression2>
>         if <condition> then <expression1> else <expression2>

On first glance, the second feels a little cleaner -- it separates
<condition> and the two <results>, whereas the first is more of a banana
sandwich (ugh).

However, it's quite hard to judge these alone without any surrounding
context. In what context do we anticipate if-then-else being used most?

Casting them in an assignment context:

x = a if <condition> else b
x = if <condition> then a else b

makes the first suddenly seem more attractive, particularly if a is the
expected result and b is an exceptional result. The second form reads like
an if statement gone wrong -- Guido worries that this is ambigous to the
parser, but I think it's worse: it's ambigious to the reader.

>         x if C else y if D else z <==> x if C else (y if D else z)

Eeek! If I saw this in code I'd have to pull up sharp and puzzle it out.
This worries me a little: readability is one of the strengths I like about
Python. That said, chained list comprehensions already have the same effect
on me.

On the subject of list comprehensions: this makes me lean towards the
if..else rather than if..then..else form. List comprehensions already use an
<expression> if <condition> form:

results = [<expression> for a in stuff if <condition>]

which is nicely similar to the proposed form. And I wonder if if/else would
be worth carrying over into list comprehensions too:

results = [<expression> for a in stuff if <condition> else <expression>]

although I can't think of any non-contrived examples. And my brain starts
hurting too much when I start imagining this with both <expressions>
themselves being if-else expressions...

I sort of like it but it also scares me silly -- it feels like a very sharp
knife to solve a fairly trivial syntactic niggle. The pre-vote discussion
period is wise: my vote is still undecided.

--
James Kew
james.kew at btinternet.com






More information about the Python-list mailing list