conditional expressions

Terry Reedy tjreedy at
Fri Sep 27 17:22:33 EDT 2002

"Alex Martelli" <aleax at> wrote in message
news:dITk9.175519$pX1.6209886 at
> A typical, frequent, practical case is classification, e.g.:
> "Append bleep to list truebleeps when bleep is true, append it
> to list falsebleeps instead when false".
> If we had a ternary operator, a natural way of expression would be:
>     (bleep?truebleeps:falsebleeps).append(bleep)

This reminds me of using ?: to calculate C lvalues (targets), which I
am not sure all C programmers realize is legal, since all examples I
read while learning only used ?: to calculate rvalues (sources).

> It's _dangerous_ -- to use it, one always has to be fully aware
> of the risk that subexpression b might be false.

If b is a non-null constant, there is no such risk.  Consider

na=1; np=3; nl=1; ng=0
print "Found: %d apple%s, %d plum%s, %d lemon%s, and %d grape%s." %\
(na, na!=1 and 's' or '', np, np!=1 and 's' or '', nl, nl!=1 and 's'
or '', ng, ng!=1 and 's' or '')

Found: 1 apple, 3 plums, 1 lemon, and 0 grapes.

Alternatives to this 'risky' construct:
1. forgo the nicety of correct English output
2. nest if/else four levels deep to choose correct variant of 16 print
statements (ugh)
3. precalculate 4 suffixes and store in 4 temp vars with 4 if/else's
(8 or 16 lines);
   though clearly superiour to 2), this is still tedious with some
risk of typo error.

To revise your statement: to properly use 'a and b or c' as a
conditional expression, one must be aware of and remember the
condition 'bool(b)==True'.  To contrapositively paraphrase what I
wrote before: if b is an expression with variables and it is not
clear that won't be null, then don't use it.  This is as clear as
"don't divide by 0 and be wary of variable expressions that might
become 0."

>  I think this is a pitfall just waiting for the unwary to stumble.

Must functions have preconditions on arguments or possibly surprising
results that can cause the 'unwary' to stumble.  'x/y', 'float -
(float+eps)' and '[[]]*n' are other examples.  Perhaps we should
better teach people "Before you use a function or language construct,
make sure you understands its input conditions and output and the
pitfalls thereof, lest you stumble due to unwariness".

Terry J. Reedy

More information about the Python-list mailing list