PEP 308 - suggestion for generalising the ternary operator

damien morton morton at dennisinter.com
Wed Feb 12 05:53:42 EST 2003


One Python implimentation of the ternary operator expresses the
problem as selecting from a list of alternatives:
[tval,fval][not cond]

I was thinking over how to generalise this into a more powerfull and
readable form and came up with this syntax:

(cond1?value1, cond2?value2, cond3?value3, default_value)

whose degenerate ternary operator form is:

(cond? true_value, false_value)

I think the parentheses should be mandatory.


Personally, I dont have a problem with the use of punctuation. The
ternary operator is an operator, and in general operators need to be
compact and consise and contrasty. This is true for all operators in
python, with the exception of 'in', 'and', 'or'.

All of the suggestions I have seen so far that use textual operators
(e.g. tokens such as 'if/then/else') seem too verbose to me, and when
I scan expressions using them, its hard for me to separate the
variables from the operators.

Heres a couple of use cases rehashed to my proposed ternary syntax:

x = (y>0? sqrt(y), 0)
ext = (is_html(text)? "html", "txt")
print "widget%s loaded" % (num>0? "s", "")

Some uses of the extended syntax:

ext = (is_html(bytes)? "html", is_mpeg(bytes)? "mpg", is_jpeg(bytes)?
"jpg", "txt")
sign = (x<0? -1, x>0? 1, 0)




More information about the Python-list mailing list