A modest indentation proposal

Skip Montanaro skip at pobox.com
Fri Nov 30 15:34:34 EST 2001


    > Skip:
    > > In Python, if it looks right, it is right.
    > 
    > No, that's not true.  Consider the following two alternative code
    > fragments:
    > 
    > if x:
    >   foo()
    > baz()
    > 
    > if x:
    >   foo()
    >   baz()
    > 
    > They both look right, but they can't both be right.

One or the other of the above alternatives will appear correct to the
programmer.  "If it looks right, it is right" means that if the programmer
looks at the second snippet and thinks, "yup, foo() and baz() should only be
executed if x is true", then it's right.  The equivalent in C (visually) is

    if (x)
       foo();
       baz();

It is a common mistake for a C programmer to look at that and think "yup,
foo() and baz() should only be executed if x is true".  Of course, that
snippet means something entirely different than its indentation implies.

Which is what I was getting at.  As others have pointed out, in most
languages, indentation is relevant for the humans that read the program, but
generally not relevant for the compilers and interpreters that analyze and
execute it.  In Python that difference doesn't exist.  Indentation is
important to the humans *and* to the Python interpreter.

There are fewer chances to make these sorts of mistakes in Python than in
the class of languages descended from C (C, C++, Java, ...).  Perl avoids
this problem by requiring BLOCKs to always be delimited by { & }.  BASIC of
most flavors (and Pascal) uses BEGIN and END I believe.  Guido chose a
different approach than taken by the designers of those languages, but it's
only different, not worse.  Many Python programmers, myself included, would
argue that it's better, though I expect most Perl and VB programmers would
probably disagree.

Cut-and-paste has been suggested as a source of problems in Python.  I've
also found that not to be a problem, given good editor support for rigidly
moving chunks of code left and right.  Python-mode uses C-c > and C-c < to
do this.  Works like a champ in those situations where I do cut-and-paste.

-- 
Skip Montanaro (skip at pobox.com - http://www.mojam.com/)




More information about the Python-list mailing list