[Python-Dev] Re: Trinary Operators

Phillip J. Eby pje@telecommunity.com
Fri, 07 Feb 2003 14:49:31 -0500


Guido van Rossum wrote:

 >  print 1 if x and y else 0

<shudder>  Up until that example, I was actually thinking adding this to 
Python would be a good idea.  But that looks just plain unreadable to 
me.  Someone with a Perl background would also likely parse the above as 
meaning:

if x and y:
     print 1
else:
     0

Which is actually a sensible thing to say in Perl.

Rendering the same example with parentheses:

print (1 if (x and y) else 0)

It's now less ambiguous, but looks like some sort of crazy infix Lisp.  :(

Maybe it would work better with parentheses required, and a little more 
verbosity?  E.g.:

print (return 1 if x and y else return 0)

For chaining, the else return could be allowed to segue into a new clause:

print (return 1 if x and y else return -1 if not z else return 0)

Or more nicely formatted:

print (
     return 1
        if x and y
     else return -1
        if not z
     else return 0
)

Hm.  I'm still not really convinced.