Defending the ternary operator

Andrew Dalke adalke at
Mon Feb 10 09:06:57 CET 2003

Martin Maney:
> Better yet, it would save otherwise kind and compassionate people from
> having to foist these wretches off on the innocent who come to them for
> assistance.

Foist?  The FAQ specifically says "in many cases .. but there's a flaw"
"ugly", "rare", and "as a last resort".

> But it's not an increase - it's a decrease.  You get one form that is
> both safe and IMO far more readable in place of at least three
> different ugly, sometimes unsafe, hacks.  (three has to be a lower
> bound, since we've seen at least one significant variation on all of
> the above just in recent pre-308 discussion)

I've been trying to show that people will be prone to use the ternary
if/else expression even when a better (by my definition of better)
option is available.  Three such are

  return True if x else False
instead of
  return bool(x)

  c=chr(48+i if i<10 else 55+i)
instead of
  c = "0123456789ABCDEF"[i]
  c = hex(i)[2:]

  a = x if x < y else y
instead of
  a = min(x, y)

Not only that, but I've been trying to show that the
misuse rate, based on analysis of existing C/C++ code,
is roughly comparable to the proper use rate.

(A true Python expert is unlikely to misuse if/else
when a better Python solution exists, but I tried to factor
in that most of the user base is not an expert.)

                    dalke at

More information about the Python-list mailing list