Which is the closest Python equivalent to Perl::Tidy?

1.7k views Asked by At

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.

4

There are 4 answers

1
Guillermo Garza On

Have you tried creating a wrapper around pythontidy? There's one for the sublime editor here.

Also, does pythontidy break up long lines properly for you? When I have a long line that ends in a tuple, it creates a new line for every entry in the tuple, instead of using Python's implied line continuation inside parentheses, brackets and braces as suggested by PEP-8.

1
Alex Martelli On

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.

3
Radomir Dopieralski On

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

0
Matthew Leingang On

I have used autopep8 for this purpose and found it handy.