[Python-Dev] Re: Re: Trinary Operators

Terry Reedy tjreedy@udel.edu
Thu, 6 Feb 2003 21:43:40 -0500


> If you try to translate this to Python using "and"/"or":
>
>     print 'Read %d file%s.' % (count, count == 1 and '' or 's')
>
> ...it doesn't work, because the empty string is false.

Invert the logic and it works fine!

print 'Read %d file%s.' % (count, count != 1 and 's' or '')

I suspect that careful use of and/or will take care of half of real
use cases for ternary (not 'trinary') operators.  IE, at least one of
the expressions is either a non-null constant, as above, or an
expression known to never be null when its condition is true.

I am -1 on the proposed <then-expr> if <cond> else <else-expr>
syntax.  To me,
<cond> if <then-expr> else <else-expr>, as in <count ==1 if '' else
's'>, would be better since it only inverts the order of 'if' and
<cond> and not also the <then-expr>.
Even better might be a semi-keyword (ie, in this context only) 'then'
so we could properly write "if count==1 then '' else 's'".  I know
several syntaxes have been proposed on various clp ternary-operator
threads over the years.

Terry J. Reedy