For review: PEP 308 - If-then-else expression
Erik Max Francis
max at alcyone.com
Sat Feb 8 04:53:28 CET 2003
Guido van Rossum wrote:
> PEP: 308
> Title: If-then-else expression
I am +1 on the addition of a conditional expression.
> The proposed syntax is as follows:
> <expression1> if <condition> else <expression2>
+0.8. I want conditional expressions and will take any form I can get,
but the condition in the middle does seem a little counterintuitive.
> Examples of how this works out:
> x if C else y if D else z <==> x if C else (y if D else z)
This is certainly the most sensible solution for chaining conditional
expressions, although chaining conditional expressions -- in whatever
language, not just Python -- is usually a sign of obfuscation. (Still,
it should "do the right thing" even if obfuscation is what you're
actively choosing, and what is proposed abovce is the right thing.)
> x or y if C else z <==> (x or y) if C else z
> x if C else y or z <==> x if C else (y or z)
> lambda: x if C else y <==> lambda: (x if C else y)
> x if C else lambda: y <==> SyntaxError
> x if C else y, z <==> (x if C else y), z
> x, y if C else z <==> x, (y if C else z)
These are all edge cases and don't bother me. Particularly the latter
two; if you're going to be inlining tuples in conditional expressions,
it doesn't hurt to be forced to use parentheses to disambiguate.
> If we could live with adding a new keyword, we could use:
> if <condition> then <expression1> else <expression2>
This would get higher ratings with me than the proposed syntax, simply
because it has the left-to-right evaluation and seems more natural. I'd
be willing to live with enforced parentheses.
But bottom line is I'll take whatever I can get. I want a conditional
expression in Python.
As for other peoples' suggestions, I think whatever the form it takes,
the "else" portion of the conditional should be required. No "x if y"
(or "if y then x") shortened versions; explicit is better than implicit,
if you want None or something else in that else then you should write it
Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/ \ Shooters, looters / Now I got a laptop computer
\__/ Ice Cube
Kepler's laws / http://www.alcyone.com/max/physics/kepler/
A proof of Kepler's laws.
More information about the Python-list