[Python-Dev] Adding a conditional expression in Py3.0

Terry Reedy tjreedy at udel.edu
Sat Sep 24 05:21:14 CEST 2005

"Greg Ewing" <greg.ewing at canterbury.ac.nz> wrote in message 
news:433223A8.3010400 at canterbury.ac.nz...
> Terry Reedy wrote:
>> Many people, perhaps most, including me, read
>> exp1 if exp2 else exp3 # as
>> cond if etrue else efalse # in direct analogy with
>> cond ?  etrue :     efalse # from C
> I'd have thought only Forth programmers would be prone to that!

Never wrote a single line, and may have not read one (in DDJ? Byte?) for 
15-20 years.  How do *you* read such C?  Cond 'Qmark' ....?

> It would surprise me greatly if it's really true that *most*
> people would read it that way.

OK.  I withdraw 'possibly most' as not directly relevant.  It would not 
take that many people to have enough people mistakenly write or read it 
that way for this construct to be somewhat as bug prone, in practice, as 

During the c.l.p debate, someone counted about 100 correct uses of 'a and b 
or c' in the standard library.  But one real misuse edged Guido toward 
replacing it.  So I think the replacement should be as clear as reasonably 
possible and clearly an improvement.

> Especially given that, in real
> code, you're not going to be looking at abstract names like
> exp1, exp2, exp3, but (hopefully) something a lot more
> meaningful.

Because every object in *Python* (ignoring buggy or unusual __nonzero__ 
methods) has a boolean value, any expression can be a conditional 
expression and hence conditional expressions often lack a boolean operator 
to flag the expression as the likely conditional.

> Can you honestly say that you would read

Given that setup, how could I possible misread :-?

>   return red_value if color == 'red' else blue_value
> as
>   if red_value:
>     return color == 'red'
>   else:
>     return blue_value
> ?

I can imagine that if I were to read the return naively, I might wonder 
whether the expressions were reversed.  And certainly, not all code I have 
read has had such obvious names.

Now, can you honestly say that you would (naively) read

  return foo if bar else baz

and be certain you knew what it meant?

Terry J. Reedy

More information about the Python-Dev mailing list