Defending the ternary operator

John Roth johnroth at ameritech.net
Mon Feb 10 07:44:12 EST 2003


"Andrew Dalke" <adalke at mindspring.com> wrote in message
news:b27mc5$bqc$1 at slb6.atl.mindspring.net...
> 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]
> OR
>   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.)

So? I've seen people do things the hard way in
just about every language I've worked in. In most
cases, all it takes is a friendly suggestion: "Wouldn't
this way be clearer?" and they go "Huh? Oh!" and
the problem goes away.

John Roth
>
>                     Andrew
>                     dalke at dalkescientific.com
>
>






More information about the Python-list mailing list