Python Formatter
Format Python code online with the Ruff formatter in Black-compatible style. Choose line length, indent and quotes; runs privately in your browser.
- Free
- No sign-up
- Runs in your browser
Python Formatter
Runs in your browser. Your inputs never leave your device.
In short
Quick Answer
Paste your code and press Format. The Ruff formatter rewrites it in Black-compatible style: 4-space indents, spaces around operators, two blank lines between top-level functions and classes, double quotes, and lines wrapped at 88 characters (or 79 for strict PEP 8). It changes only layout, not behaviour, and reports syntax errors with a line number instead of guessing a fix.
Step by step
How to Use
- Paste your code. Paste a Python snippet or whole file into the input box, or load the example.
- Choose options. Pick a line length (88 by default), indent width and quote style.
- Format. Press Format or Ctrl+Enter. Fix any syntax error at the reported line, then format again.
- Copy the result. Copy the formatted code from the output box.
PEP 8 basics
PEP 8 is Python's official style guide. A formatter applies the mechanical parts of it for you, so you can spend review time on what the code does rather than how it is laid out. The rules it enforces most often are:
- Four spaces per indentation level. Spaces, not tabs, and never a mix of the two in one block.
- A limited line length. PEP 8 recommends 79 characters for code and 72 for comments and docstrings, so that two files fit side by side and diffs stay readable.
- Blank lines with meaning. Two blank lines around top-level functions and classes, one blank line between methods inside a class.
- Spaces around operators. One space either side of assignment and comparison operators (
x = y + 1,if total >= limit), but no spaces around=in keyword arguments and defaults (def f(rate=0.18)). - No extra spaces inside brackets and one statement per line, so
a = 1; b = 2becomes two lines.
Naming conventions, such as snake_case for functions and variables and CapWords for classes, are also part of PEP 8, but a formatter never renames anything. That is a job for a linter and for code review.
How Ruff and Black style differs from plain PEP 8
PEP 8 leaves many choices open, and two people following it can still lay out the same code differently. Black, and the Ruff formatter that copies its style, remove those choices so every file in a project looks the same:
- 88 columns instead of 79. Black chose 88 because it produces noticeably shorter files than 79 while still fitting comfortably on screen. Choose 79 here if your project follows PEP 8's limit strictly.
- Double quotes by default. PEP 8 allows either quote style as long as you are consistent; Black standardises on double quotes. Ruff adds the option to prefer single quotes or to keep existing ones.
- Predictable wrapping. When a call, list or dictionary is too long, it is split one item per line with a trailing comma, so adding an item later changes only one line in the diff.
- The magic trailing comma. If you leave a trailing comma after the last item, the formatter keeps the expression expanded even when it would fit on one line.
Because the output is the same no matter who runs it, teams usually format on save or in a pre-commit hook and stop discussing layout in reviews.
Errors the formatter cannot fix
The formatter first parses your code into a syntax tree, and only then prints it back out in a consistent style. If parsing fails, there is nothing to format, so it reports an error with the line and column instead of guessing what you meant:
- IndentationError and TabError. Mixing tabs and spaces, or indenting a line more than its block, makes the structure ambiguous. The formatter reports "Unexpected indentation" at the first such line.
- Syntax errors. A missing colon after
deforif, an unclosed bracket or an unterminated string stops parsing. An unclosed bracket is often reported on the next line, because that is where Python realises the expression did not end. - Problems a linter finds. Unused imports, undefined names or a shadowed variable are valid syntax, so the formatter leaves them alone.
When the formatter reports an error, the cursor jumps to that position in the input so you can fix it and format again.
Private by design
This page runs the Ruff formatter compiled to WebAssembly. The engine is served from this site and only downloaded when you first format code on this page; after that it runs entirely in your browser, so proprietary or unpublished code never leaves your device. For other languages, see the Java Formatter, or the JSON Formatter for data files.
Examples
Worked Examples
A cramped function
Before
def calculate_total( items,tax_rate = 0.18 ) :
subtotal=sum( item['price']*item['qty'] for item in items )
return subtotal*( 1+tax_rate )
After
def calculate_total(items, tax_rate=0.18):
subtotal = sum(item["price"] * item["qty"] for item in items)
return subtotal * (1 + tax_rate)
Result: Spaces around = and * are normalised, the default argument loses its spaces, the body is indented with 4 spaces, and single quotes become double quotes.
A long dictionary
Before
config = {'host':'localhost','port':5432,'database':'inventory','user':'admin','options':{'sslmode':'require','connect_timeout':10}}
After
config = {
"host": "localhost",
"port": 5432,
"database": "inventory",
"user": "admin",
"options": {"sslmode": "require", "connect_timeout": 10},
}
Result: The line is longer than 88 characters, so each key moves to its own line with a trailing comma. The nested dictionary still fits on one line, so it stays there.
A class with crowded methods
Before
class Account :
def __init__(self,owner,balance=0):
self.owner=owner;self.balance=balance
def deposit(self,amount):
if amount<=0: raise ValueError('Deposit must be positive')
self.balance+=amount
return self.balance
After
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit must be positive")
self.balance += amount
return self.balance
Result: The two statements joined by a semicolon are split onto separate lines, the one-line if body is expanded, and a blank line separates the methods.
Watch out
Common Mistakes to Avoid
- Mixing tabs and spaces: Python treats a tab and spaces as different indentation, so a block that mixes them raises IndentationError or TabError. The formatter cannot parse such code and reports "Unexpected indentation" with a line number. Re-indent that block with spaces only, then format again.
- Expecting the formatter to fix syntax errors: A missing colon, bracket or quote makes the file unparseable. The formatter only rearranges valid code, so fix the error at the reported line first. The line it reports can be just after the real mistake, such as the line following an unclosed bracket.
- Expecting imports to be sorted or split: Formatting keeps import os, sys as written. Splitting one import per line and sorting imports are linter jobs, done by Ruff's lint rules or isort, not by the formatter.
- Not agreeing on a line length: If one person formats at 79 columns and another at 88, every file changes back and forth. Pick one value for the project and keep it in a shared configuration, such as line-length in pyproject.toml.
- Leaving a trailing comma you do not want: A trailing comma after the last item tells the formatter to keep a call or collection expanded one item per line, even if it would fit on one line. Remove the comma if you want it collapsed.
FAQ
Frequently Asked Questions
How do I format Python code online?
Paste your code into the box, choose a line length, indentation and quote style, and press Format or Ctrl+Enter. The formatted code appears below, ready to copy. The formatter runs in your browser, so your code is not uploaded.
Is this the same as Black?
It uses the Ruff formatter, which is designed as a drop-in replacement for Black and produces near-identical output on Black-formatted code. Unlike Black, Ruff lets you choose the quote style.
What line length does PEP 8 recommend?
PEP 8 recommends a maximum of 79 characters for code and 72 for comments and docstrings, and allows teams to agree on up to 99. Black and Ruff default to 88, which is why 88 is the default here.
Why does the formatter say "Unexpected indentation"?
A line is indented more than the block it belongs to, often because tabs and spaces are mixed or a line was pasted with extra indentation. Fix the indentation at the reported line so each block uses the same number of spaces.
Does the formatter change single quotes to double quotes?
Yes, by default, to match Black. Choose Single to prefer single quotes, or Preserve to keep each string's existing quotes. Quotes are only swapped when that does not require extra escaping.
Will formatting change how my code runs?
No. The formatter only changes whitespace, line breaks, quotes and parentheses that do not affect meaning. If the code cannot be parsed, it stops with an error rather than changing anything.
What is the difference between a formatter and a linter?
A formatter rewrites layout automatically. A linter reports problems such as unused imports, undefined names or risky patterns, and only some of those can be fixed automatically. Most projects use both.
Is my code uploaded to a server?
No. The Ruff formatter is compiled to WebAssembly and served from this site; it downloads the first time you format and then runs inside your browser.
References