Python indentation

Ville Vainio ville at spammers.com
Thu Jul 8 05:38:30 EDT 2004


>>>>> "Antoon" == Antoon Pardon <apardon at forel.vub.ac.be> writes:

    Antoon> I would prefer to indent sucu code as follows:

    Antoon> while True:
    Antoon>   code
    Antoon> if condition: break
    Antoon>   code


    Antoon> Why? because the loopbreaker is IME part of the
    Antoon> loopstructure, not an ordinary if statement in the
    Antoon> loopbody.

It's still going against the underlying block structure, so a source
code "prettifier" would screw it up even if Python allowed it.

BTW, every time this indentation issue comes up I'd like to point
people to pindent.py in Tools/scripts directory. It augments source
with block closing comment (and vice versa), like this:

def foobar(a, b):
   if a == b:
       a = a+1
   elif a < b:
       b = b-1
       if b > a: a = a-1
       # end if
   else:
       print 'oops!'
   # end if
# end def foobar

The script is either in:

Python23/Tools/Scripts/pindent.py  (DOS)
/usr/share/doc/python2.3/examples/Tools/scripts/pindent.py (Debian)

    Antoon> This is why I prefer free form languages. If you need
    Antoon> certain control structure that is not directly in the
    Antoon> language but can be simulated, you can still indent your
    Antoon> code according to the structure you have in mind as
    Antoon> opposed to the structure that is forced upon you by the
    Antoon> simulation.

You realize that this approach is slightly heretical, do you?
Indentation should follow the "real" block structure *exactly*,
anything else is an error that confuses the reader. 

The while 1 - break structure doesn't even need extra clarification,
because the break is typically in a very idiomatic place - right after
the assignment in the beginning, or at the very end if it's
semantically a repeat-until loop (which are rare).

-- 
Ville Vainio   http://tinyurl.com/2prnb



More information about the Python-list mailing list