keeping Python code properly indented

Harry George harry.g.george at boeing.com
Thu Jan 15 08:40:44 EST 2004


beliavsky at aol.com writes:

> How do you keep Python code properly indented as you modify it? I use
> an Emacs-type editor that has a Python mode, so the initial indenting
> is easy. If I later want to put a 'for' loop (or an 'if' statement)
> around a bunch of code, I find myself going through the body of the
> loop, manually re-indenting to keep the nested loops correct. There
> should be a better way.
> 
> I think that having a 'for' loop end with a matching 'next' statement,
> as done in (for example) Basic, is a safer and clearer way of writing
> loops, although some Python programmers consider this a 'feature'
> rather than a 'bug'.

You do not need to "go through the body, manually re-indenting".  In
emacs, block select everything to be indented and then do the right
shift in one step.  That action is in the python-mode.el's added menu,
and it is available as keystrokes ("C-c >" by default).  Similarly for
undenting.

Is there a safety concern which requires solution through closure
markers?  It is a potential problem, but isn't worth closure markers
in the language.  The main solution is to not let indenting get out of
whack in the first place:

a) Have a rigorous newbie setup process to assure the editor does
4-char hard spaces (no tab chars), and understands python-mode
indenting.   See: http://www.python.org/peps/pep-0008.html

b) During development, run unittest-based regression tests every
minute or so.  A messed-up indent will either fail to compile or will
fail a test.  This enforces the indents and that becomes valued a
language feature when doing code reviews.

c) Immediately fix indents if problems are detected.

d) Keep the code under revision control, so older (known good) code
can be recovered.

(If you can't assure a-d, then there are bigger problems than language
features.)

Finally, if you really think you need closure markers, 
do so with comments instead of language changes:

    if x > y:
      z=0
    #end if

You will still be forced to get the indenting right, but at least you
will have clues for recovering mangled indenting.

-- 
harry.g.george at boeing.com
6-6M31 Knowledge Management
Phone: (425) 342-5601



More information about the Python-list mailing list