views:

303

answers:

2

I have some existing code which isn't formatted consistently -- sometimes two spaces are used for indent, sometimes four, and so on. The code itself is correct and well-tested, but the formatting is awful.

Is there a place online where I can simply paste a snippet of Python code and have it be indented/formatted automatically for me? Alternatively, is there an X such that I can do something like X --input=*.py and have it overwrite each file with a formatted version?

+8  A: 

Use reindent.py. It should come with the standard distribution of Python, though on Ubuntu you need to install the python2.6-examples package.

You can also find it on the web.

This script attempts to convert any python script to conform with the 4-space standard.

unutbu
Great suggestion! `reindent.py` is invaluable and has become a standard part of my dev toolkit.
jathanism
Perfect. Thanks! I used `find . -type f -name "*.py" | xargs python reindent.py --nobackup`.
John Feminella
+1  A: 

Some editors have an auto-format feature that does this for you. Eclipse is one example (though you would probably have to install a python plug-in).

Have you checked whichever editor you use for such a feature?

Chris
+1 for eclipse autoformatting. Just open up the file and resave it in eclipse. It will fix the indentation, delete erroneous spaces between parenthesis and args, add spaces after commas in lists and args, add correct spacing around "=" signs, and all the other PEP 8 goodness.
Brendan Abel