pythonformattingcode-formatting

How do I autoformat some Python code to be correctly formatted?


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?


Solution

  • Edit: Nowadays, I would recommend autopep8, since it not only corrects indentation problems but also (at your discretion) makes code conform to many other PEP8 guidelines.


    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.