Python Formatter

Rebuild Python indentation at one consistent width, turning mixed tabs and ragged spacing into clean PEP 8 levels.

Python source
Formatted Python
Runs locally in your browser

About the Python Formatter

Python is the one language where indentation is not decoration, so this formatter works differently from the others in this category. It cannot invent structure, because the nesting you typed is the program. What it does instead is read the levels already present, push each new depth onto a stack, and reprint the file so that every level is exactly the same number of spaces. A file that wanders between three, eight and twelve spaces comes back as a clean ladder of four.

Tabs are expanded to spaces first, which fixes the most common cause of an IndentationError: a file where some lines use tabs and others use spaces. Continuation lines inside open brackets or after a trailing backslash are given one extra level so a long function call or a multi line list reads clearly. Triple quoted strings and docstrings are copied out with their internal whitespace untouched, since changing it would change the value of the string.

The block structure is checked as it goes. If a line ends with a colon and the next real line is not indented further, that is reported with both line numbers rather than silently guessed at, because there is no correct way to recover the missing block. Comment lines are skipped when looking for that next line, so a commented header inside a function is not mistaken for the body.

This is not black. Nothing is rewrapped, no quotes are normalised and no blank lines are inserted between functions. It is the fix for pasted code that lost its shape. To turn a JSON document into Python literals, see JSON to Python.

How to use

  1. Paste your Python into the left pane, or press Sample to load a script with deliberately uneven indentation.
  2. Leave Indent at 4 spaces for PEP 8, or choose 2 if your project uses the tighter style.
  3. If an error names two line numbers, add the missing indented block at the line it points to and run again.
  4. Save the result with Download as formatted.py.

Common questions

Can it fix code that has lost all of its indentation?
No, and no tool can. Once every line is flush left the block structure is gone. You have to restore the nesting by hand; this page then makes it consistent.
Does it convert tabs to spaces?
Yes. Every tab is expanded to four columns before the levels are measured, which removes the mixed indentation error that Python raises for such files.
Are docstrings reindented?
The opening line is placed at the right level and the body of the triple quoted string is left exactly as written, because those characters are part of the string value.
Is this the same as running black or autopep8?
No. Those rewrite line breaks, quotes and spacing around operators. This page only normalises indentation levels, which is the part that survives copying and pasting badly.