views:

125

answers:

2

Coming from Perl I've been used to hitting C-c t to reformat my code according to pre-defined Perl::Tidy rules. Now, with Python I'm astonished to learn that there is nothing that even remotely resembles the power of Perl::Tidy. PythonTidy 1.20 looks almost appropriate, but barfed at first mis-aligned line ("unexpected indent").

In particular, I'm looking for the following:

  • Put PEP-8 into use as far as possible (the following items are essentially derivations of this one)
  • Convert indentation tabs to spaces
  • Remove trailing spaces
  • Break up code according to the predefined line-length as far as it goes (Eclipse-style string splitting and splitting method chains)
  • Normalize whitespace around
  • (bonus feature, optional) Re-format code including indentation.

Right now, I'm going throught someone else's code and correct everything pep8 and pyflakes tell me, which is mostly "remove trailing space" and "insert additional blank line". While I know that re-indentation is not trivial in Python (even though it should be possible just by going through the code and remembering the indentation), other features seem easy enough that I can't believe nobody has implemented this before.

Any recommendations?

Update: I'm going to take a deeper look at PythonTidy, since it seems to go into the right direction. Maybe I can find out why it barfs at me.

+1  A: 

There is a reindent.py script distributed with python in the scripts directory.

Radomir Dopieralski
It available from PyPi and doesn't work properly -- a mis-indented file is not corrected. Apparently, only valid indentations are changed, e.g. from 2 spaces to 4.
rassie
An incorrectly indented file might be ambiguous, how would a script know what you really mean?
Nick T
@Nick: first line of code shouldn't be ambiguous, especially when it's `from foo import baz`.
rassie
A: 

untabify.py (Tools/scripts/untabify.py from the root directory of a Python source distribution) should fix the tabs, which may be what's stopping Python Tidy from doing the rest of the work.

Alex Martelli
Yes, Emacs does that too with its `untabify` command. But that's just one problem, which is a non-issue after an initial conversion.
rassie