Inconsistent spacing, mixed quotes and 150-character lines make Python harder to read and review. A formatter fixes all of it in one step. Here is how to set one up — or format a snippet online in seconds.
A formatter rewrites the layout of your code — indentation, spaces, line breaks, quotes, blank lines — without changing what it does. Here is a messy function before formatting:
import os,json
def load_config(path,defaults={ 'debug':False,'retries':3 }):
if not os.path.exists(path): return defaults
with open(path) as f:
data=json.load(f)
return {**defaults,**data}
And the same code after running Black, the most widely used Python formatter:
import os, json
def load_config(path, defaults={"debug": False, "retries": 3}):
if not os.path.exists(path):
return defaults
with open(path) as f:
data = json.load(f)
return {**defaults, **data}
Indentation is now 4 spaces, there is a space after every comma, the two top-level statements are separated by blank lines, and quotes are consistent. Nothing about the program's behaviour has changed.
For a snippet, a file from someone else or code an AI assistant gave you, the fastest option is the free Python Formatter. Paste the code, pick a line length and click Format code. It runs the real Black, so the result is identical to running it on your machine — and if the code has a syntax error, it tells you the line and column.
Paste any Python and get clean, Black-formatted code. Choose line length 79, 88, 100 or 120.
Open the Python FormatterInstall Black with pip and point it at a file or a whole folder:
pip install black
black app.py # format one file
black . # format every .py file under the current folder
black --check . # report files that would change, without changing them
black --diff app.py # show the changes as a diff
black --check exits with an error when a file isn't formatted, which makes it useful in CI to keep unformatted code out of your main branch.
Black deliberately has very few options. The two you are most likely to want go in pyproject.toml so everyone on the project gets the same result:
[tool.black]
line-length = 100
skip-string-normalization = true # keep 'single' quotes as they are
ms-python.black-formatter)."[python]": {
"editor.defaultFormatter": "ms-python.black-formatter",
"editor.formatOnSave": true
}
Every time you save a Python file, it is formatted with Black, using the settings from your pyproject.toml. PyCharm has the same feature built in under Settings → Tools → Black.
With pre-commit, Black runs on the files you're committing, so unformatted code never reaches the repository. Add a .pre-commit-config.yaml:
repos:
- repo: https://github.com/psf/black
rev: 24.10.0
hooks:
- id: black
Then run pip install pre-commit and pre-commit install once in the repository.
If a call or definition doesn't fit within the line length, Black first tries to wrap it; if it still doesn't fit, it puts each argument on its own line and adds a trailing comma:
def find_orders(customer_id, status='open', limit=50, include_archived=False, sort_by='created_at', fields=None):
pass
def find_orders(
customer_id,
status="open",
limit=50,
include_archived=False,
sort_by="created_at",
fields=None,
):
pass
This is Black's "magic trailing comma". If you end a collection with a comma, Black keeps one item per line even when it would fit on one line:
values = [
1, 2, 3,
]
values = [
1,
2,
3,
]
Remove the trailing comma and Black will join it back onto one line. It's a simple way to choose the layout yourself.
For a hand-aligned table or matrix you want to keep as is, wrap it in # fmt: off and # fmt: on, or put # fmt: skip at the end of a single line.
black . for whole projects, with options in pyproject.toml.