4

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.

Nikolai Prokoschenko
  • 7,353
  • 6
  • 48
  • 89

4 Answers4

1

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

Radomir Dopieralski
  • 2,441
  • 15
  • 14
0

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
  • 762,786
  • 156
  • 1,160
  • 1,345
0

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

Matthew Leingang
  • 2,049
  • 3
  • 17
  • 16
0

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.

Guillermo Garza
  • 1,006
  • 1
  • 9
  • 8
  • 1
    An official wrapper by the author of PythonTidy exists [here](http://lacusveris.com/PythonTidy/PythonTidyWrapper.python). I've had a couple of problems with PythonTidy initially and have mailed the author, who prompty released a [PythonTidy 1.21](http://lacusveris.com/PythonTidy/PythonTidy-1.21.python), which is not linked from PyPI. I'm still not fully satisfied, but I haven't had the time to note every problem and/or patch it appropriately. – Nikolai Prokoschenko Feb 27 '11 at 18:07