For review: PEP 308 - If-then-else expression

Andrew Dalke adalke at mindspring.com
Mon Feb 10 01:35:07 EST 2003


James J. Besemer:
> David Eppstein wrote:
>
> > Turn it around a little and both versions become a little clearer:
> >
> > "customer" if "spam" not in s else "vikings" if "eggs" in s else
> > "waitress"
> >
> > if "spam" not in s:
> >     t = "customer"
> > elif "eggs" in s:
> >     t = "vikings"
> > else:
> >     t = "waitress"

> E.g., if you
> look closely you'll find a subtle bug in the above if/else example.  This
> typo would be IMPOSSIBLE to make with inline choice.  Thus the supposedly
> "more readable" form admits a class of errors the inline form prohibits.
And
> this is a class of errors that easily go undetected in a declaration free
> language like Python.

What's the typo?  Note that the rewrite here was not the same as my
original code, which is

if "spam" in s:
  if "eggs" in s:
    t = "vikings"
  else:
    t = "waitress"
else:
  t = "customer"

> So to flatly claim that the if/else form is superior to inline choice is
> simply untrue.  From the big picture standpoint, inline choice is equally
> useful and understandable.

I agree that there are times when the if/else expression make the code
more readable and more maintainable.

My claim these days (it's changed over the progression of this thread ;)
is that the if/else expression will be used inappropriately, and the rate
of misuse will be roughly equal to the amount of proper use.

(The numbers differ given the codebase.  In one C++ codebase
written by people who don't consider themselves to be expert
programmers, the misuse rate in C++ was higher than the proper
use rate, and if the code had been written in Python then the
misuse rate would have been even higher.  In another C codebase
(Python's C implementation, written by experts) the estimated
misuse rate from a small sample of examples was about 1 misuse
for every 2 uses.)

I gave elsewhere examples of misuse, including

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

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

I do not believe this discussion of the likely misuses of the
if/else expression have been sufficiently considered.

Actually, there have been statements about "hobbling good
programmers based on the follies of bad one".  I've then
suggested that this construct will only be used about 1 every
1,000 lines (others suggest numbers closer to 1 every 200,
but have have problems with that analysis).  So the "hobbling"
part will be minor in the best of cases.  Granted, that also
means the misuse will be low, but that means 1/2 the time
you see this construct in others' code, it will be used
incorrectly.

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list