Sub topic 8
Formatting code with ruff format
This chapter covers ruff format, the formatter built into Ruff. It assumes you can run Ruff from a terminal, read a pyproject.toml file, and already know what ruff check does. Linting is covered in earlier chapters, so this chapter stays on formatting.
What the formatter does
ruff format rewrites Python files so that whitespace, quotes, line breaks, and trailing commas follow one consistent style. It never changes what the program does. It only changes how the source looks. Its output is designed to match Black, the formatter it was modeled on, for the vast majority of code. A small number of deliberate differences exist, so do not expect a byte-for-byte match on every file in a large codebase.
The formatter is deterministic. The same input and the same settings always produce the same output. Running it a second time on already formatted code changes nothing. This property is called idempotence, and it is what makes ruff format --check useful in CI.
Running the formatter
The basic commands are:
ruff format .
ruff format src/app.py
ruff format --check .
ruff format --diff .ruff format .rewrites every Python file under the current directory.ruff format src/app.pyformats one file.ruff format --check .changes nothing. It lists the files that would change and exits with status 1 if there are any.ruff format --diff .prints a unified diff of the changes it would make and also changes nothing.
Use --diff when you want to review what the formatter will do before you let it write to disk. Use --check in automation, where only the exit code matters.
Exit codes
| Command | Exit code 0 | Exit code 1 | Exit code 2 |
|---|---|---|---|
| `ruff format .` | Run finished | Not used for formatting changes | Invalid configuration or a file that cannot be parsed |
| `ruff format --check .` | No file would change | At least one file would change | Invalid configuration or a file that cannot be parsed |
A file with a syntax error is not formatted. Ruff reports the error and leaves the file as it was. Fix the syntax first.
A before and after example
Here is unformatted code:
# Before ruff format
x = { 'a':1,
'b':2 }
def f(a,b):
return a+bAfter ruff format:
# After ruff format
x = {"a": 1, "b": 2}
def f(a, b):
return a + bFour things changed:
- Single quotes became double quotes.
- Spaces were added after colons and commas, and removed inside the braces.
- The dictionary was collapsed onto one line because it fits within the line length.
- Two blank lines were placed before the top-level function.
How line breaking works
The formatter tries to fit each statement on one line. If it does not fit within the configured line length (88 characters by default), the formatter splits it at brackets and puts each element on its own line.
The "magic trailing comma" is the most important rule to understand. If a collection, call, or signature already ends with a comma before the closing bracket, the formatter keeps it split across lines, even when it would fit on one line.
# The trailing comma after 2 keeps this expanded.
values = [
1,
2,
]
# No trailing comma, and it fits, so it is collapsed.
other = [3, 4]This gives you a way to control the layout. Add a trailing comma to keep a list vertical, and remove it to let the formatter join the elements. When the formatter has to split a long collection itself, it adds the trailing comma for you.
The formatter does not break long strings or comments. A string that exceeds the line length stays as it is. If you need to keep such lines short, shorten them by hand.
Configuring the formatter
Formatter options live in the [tool.ruff.format] table in pyproject.toml. Two settings sit above it, in [tool.ruff], because the linter uses them too: line-length and target-version.
[tool.ruff]
line-length = 88
target-version = "py311"
[tool.ruff.lint]
select = ["E4", "E7", "E9", "F", "I", "B", "UP"]
ignore = []
[tool.ruff.lint.per-file-ignores]
"__init__.py" = ["F401"]
[tool.ruff.format]
quote-style = "double"
indent-style = "space"
docstring-code-format = trueThe linter sections are shown here only because they come from the same file. The settings that affect formatting are:
| Setting | Default | Effect |
|---|---|---|
| `line-length` | 88 | Maximum line width the formatter aims for |
| `target-version` | inferred from `requires-python` if present | Python version whose syntax the output may use |
| `quote-style` | `"double"` | `"double"`, `"single"`, or `"preserve"` |
| `indent-style` | `"space"` | `"space"` or `"tab"` |
| `skip-magic-trailing-comma` | `false` | If `true`, ignore existing trailing commas when deciding to split |
| `line-ending` | `"auto"` | `"auto"`, `"lf"`, `"cr-lf"`, or `"native"` |
| `docstring-code-format` | `false` | Format code examples inside docstrings |
Quote style
quote-style = "double" converts strings to double quotes. It does not do so when that would add more backslash escapes. For example, 'say "hi"' stays single-quoted because switching would require escaping the inner quotes. Set "preserve" if you do not want any quote changes, which is useful during a gradual migration.
Docstring code
With docstring-code-format = true, the formatter finds code examples inside docstrings and formats them. It recognizes doctest lines starting with >>>, Markdown fenced blocks, and reStructuredText code blocks. A related option, docstring-code-line-length, sets the width for that embedded code. It accepts a number or "dynamic", which fits the embedded code to the remaining space in the docstring.
Formatting regions: `fmt: off` and `fmt: skip`
Sometimes hand-aligned code is clearer than the formatter's output, such as a matrix literal. Pragma comments tell the formatter to leave code alone.
# fmt: off
matrix = [
1, 0, 0,
0, 1, 0,
0, 0, 1,
]
# fmt: on
result = compute( 1,2 ) # fmt: skip# fmt: offand# fmt: onmark a region that is left untouched.# fmt: skipat the end of a line leaves that single statement untouched.
These comments are the formatter's equivalent of noqa. Use them sparingly, because every skipped region is code that no longer follows the shared style.
Formatting Jupyter notebooks and stdin
ruff format also handles Jupyter notebooks (.ipynb files). It formats the code cells and leaves outputs and metadata alone.
To format code from standard input, which editors and scripts use, pass - and an optional file name for configuration lookup:
cat messy.py | ruff format --stdin-filename messy.py -The formatted code is printed to standard output. The --stdin-filename option lets Ruff find the right configuration file and apply per-file settings.
Selecting files
By default Ruff respects .gitignore and skips common directories such as .git, .venv, and node_modules. You can change this in [tool.ruff]:
[tool.ruff]
extend-exclude = ["migrations", "generated"]exclude replaces the default list, while extend-exclude adds to it. Prefer extend-exclude unless you want to take over the whole list. If you pass a path on the command line, files that match an exclude are still skipped unless you use --no-force-exclude's opposite behavior. In practice, set force-exclude = true when a tool such as pre-commit passes files explicitly and you still want exclusions honored.
Interaction with the linter
The formatter and the linter both have opinions about layout, and some lint rules conflict with formatter output. Rules that control quotes, line length, and indentation are the usual causes. Examples are E501 (line too long) and the Q (flake8-quotes) family. If the formatter leaves a long string that E501 then flags, you get a violation you cannot fix with ruff format.
Ruff warns when your configuration enables a rule known to conflict. The common remedy is to not select the conflicting rules at all. The default rule set does not select E501, which is one reason the example above selects E4, E7, and E9 instead of all of E.
The practical order is to run the fixer first and the formatter second:
ruff check --fix .
ruff format .Auto-fixes can leave code in a shape the formatter would change, such as removed imports that leave extra blank lines. Formatting last gives a stable result.
Import sorting
The I rules sort imports, and ruff format does not. The formatter only normalizes whitespace and quotes in import lines. If you want sorted imports, you need I selected and ruff check --fix run, as shown above.
Verifying formatting in CI
A CI job should fail when any file is unformatted:
ruff format --check .Pair it with the lint command in the same job. Pin the Ruff version in your dependencies, because formatter output can change between releases. A new version occasionally reformats edge cases, and an unpinned CI job would start failing without any change to your code.
The formatter also warns that some rules are unsafe to combine with it. Treat those warnings as configuration errors, not noise.
Common mistakes
- Running
ruff check --fixand assuming the code is formatted. The linter and the formatter are separate commands. - Expecting
ruff formatto sort imports. It does not. - Setting
line-lengthin only one place and getting different results from the linter and the formatter. The setting under[tool.ruff]applies to both. - Using a bare
# fmt: offwithout a matching# fmt: on. The rest of the enclosing block stays unformatted. - Leaving Ruff unpinned, then seeing a formatting diff after an upgrade.
Exercise
A CI job runs ruff format --check . and exits with status 1. What does that mean, and what command fixes it locally? Also, what does a trailing comma after the last element of a list do to the formatter's output?
Show answer
Status 1 means at least one file would be changed by the formatter. Run ruff format . locally, review the changes, and commit them. A trailing comma after the last element (the magic trailing comma) makes the formatter keep the list split across lines, one element per line, even if it would fit on one line.
Exercise
Your pyproject.toml sets quote-style = "single", but one line still contains 'say "hi"' in single quotes and another contains "it's" in double quotes. Why did the formatter leave the second one alone, and which setting would stop all quote changes?
Show answer
Changing "it's" to single quotes would require an escaped apostrophe, and the formatter avoids a change that adds backslash escapes. Setting quote-style = "preserve" stops all quote changes.