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

Andrew Koenig ark at research.att.com
Sat Feb 8 10:05:42 EST 2003


Greg> BTW: In my first (and second) reading of the 2 code snippets
Greg> above, I missed the ( ) around the if-then-else, so I was
Greg> reading it that the if i<0 test ran first, and only if it's
Greg> false did the 'for' statement/clause run.  Now you can certainly
Greg> argue that I was being careless in reading the code, but is the
Greg> savings of a few lines of code really worth the potential for
Greg> confusion when another developer looks at and has to support the
Greg> code?

I am not going to argue about whether you're being careless.
Rather, I'm going to argue that the alternative that you find
harder to understand is the one that I find easier to understand.
More generally, I think that difficulty of understanding is closely
related to length * unfamiliarity.

When a new idea appears in a programming language, it usually makes it
possible to write shorter programs at the expense of making them more
familiar.  So the new programs are sometimes easier to understand than
the old and sometimes harder.

As the new idea becomes more familiar, the programs become more
familiar too, hence easier to understand.  Then everyone wins.

Here's an example from another part of Python that I hope will be
noncontroversial.  Suppose I write this:

        for i in range(n):
                print i

If you don't know the exact meaning of range, and how it interacts
with for-statements, you're stuck.  If, on the other hand, I write

        i = 0
        while i < n:
                print i
                i = i + 1

no one with any programming experience will have the slightest
difficulty understanding what I mean.  So if I were teaching Python to
rank beginners, I might well prefer the second of these forms; but
otherwise I'll use the first.  Once you're familiar with it, it's
shorter, hence easier to understand.

I think the same kind of argument applies to conditional expressions.
In some circumstances, they make programs significantly shorter.  If
you're unfamiliar with them, the unfamiliarity compensates for the
brevity, which means that some people will find them a disadvantage.
But I think that disadvantage will go away with familiarity.

-- 
Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark




More information about the Python-list mailing list