Sub topic 7
Fixing violations automatically
This chapter assumes you can run ruff check and read its output, and that you know rule codes such as F401. It covers what --fix changes, the difference between safe and unsafe fixes, and how to control both in pyproject.toml.
What a fix is
Many Ruff rules attach a fix to their diagnostic. A fix is a set of text edits that Ruff knows will remove the violation. Not every rule has one. F821 (undefined name) cannot be repaired mechanically, because Ruff cannot guess what you meant.
In the default output, a diagnostic that has a fix is marked with [*]. The summary line also counts how many violations are fixable. The exact wording changes between Ruff versions, so read your own output instead of matching the text in this chapter.
Each fix is classified as safe or unsafe:
| Kind | Meaning | Applied by |
|---|---|---|
| Safe | Keeps runtime behavior and does not delete comments. | `ruff check --fix` |
| Unsafe | May change behavior, or may delete comments or other content. | `ruff check --fix --unsafe-fixes` |
The classification belongs to the rule, not to the call. A rule can also change class depending on context. For example, removing an unused import is safe in an ordinary module. In an __init__.py file it is unsafe, because the import may be part of the package's public interface.
Applying safe fixes
Start from the file used earlier in this tutorial:
import os
import sys
def total(items):
unused = 1
result = 0
for i in items:
result += i
if result == None:
return 0
return result
print(sys.argv)This triggers F401, F841 and E711. Run:
ruff check --fix example.pyRuff removes import os, because F401 has a safe fix here. It leaves unused = 1 and result == None in place and reports them as remaining violations. The command then exits with status 1, because violations remain. Ruff also tells you that some fixes were hidden and can be enabled with --unsafe-fixes.
The two remaining rules have unsafe fixes for specific reasons:
E711rewritesresult == Nonetoresult is None. Ifresultis an object that overloads==, such as a NumPy array, the two forms behave differently.F841deletes an assignment. The deleted line may have had a side effect on the right-hand side, or a comment attached to it.
Previewing before you change files
Preview fixes before you apply them, especially unsafe ones:
ruff check --diff example.py
ruff check --diff --unsafe-fixes example.py--diff prints a unified diff of the changes and writes nothing to disk. It is the quickest way to see what a rule's fix does on your code. Once you accept the diff, apply it:
ruff check --fix --unsafe-fixes example.pyThe file is now:
import sys
def total(items):
result = 0
for i in items:
result += i
if result is None:
return 0
return result
print(sys.argv)Ruff did exactly what the rules promised, and the program is still wrong in a way no linter fixes. result starts at 0 and is never None, so the if branch is dead code. A fix removes the violation, not the logic error behind it. Always read the diff.
How fixing works internally
Ruff does not apply one fix and stop. It runs the linter, collects every fix, and applies the ones that do not overlap. A fix whose text range overlaps one already applied is skipped for that pass. Ruff then re-lints the new text and repeats until nothing changes. The number of passes is capped, so a pair of rules whose fixes undo each other cannot loop forever.
This loop explains two behaviors you will see:
- One run of
--fixcan resolve violations that did not exist when you started. For example, removing an unused import can leave a blank-line or import-order violation that the next pass fixes. - Fixes for the same region may take several passes, but you only run the command once.
Controlling which rules may fix
Two settings under [tool.ruff.lint] decide which rules are allowed to fix at all:
fixablelists the rules whose fixes may be applied. The default is every rule.unfixablelists rules whose fixes must never be applied, even when you pass--fix.
Both accept codes and prefixes, like select and ignore. A rule in unfixable is still reported. Only the automatic edit is disabled.
[tool.ruff]
fix = true
[tool.ruff.lint]
select = ["E4", "E7", "E9", "F", "I", "B", "UP"]
unfixable = ["B"]The top-level fix = true makes a plain ruff check behave as if you had passed --fix. Use it with care in shared configuration, because every ruff check run, including one in CI, then rewrites files. A CI job usually should not do that. You can override the setting on the command line with --no-fix.
unfixable = ["B"] fits a common policy. The bugbear rules often flag real bugs, and you want a person to look at each one instead of having Ruff rewrite it.
Changing a fix's safety
You can reclassify a fix without turning the rule off:
[tool.ruff.lint]
extend-safe-fixes = ["F841"]
extend-unsafe-fixes = ["F401"]extend-safe-fixespromotes the named rules' unsafe fixes to safe.ruff check --fixwill then apply them. Do this only for rules you have reviewed against your own code.extend-unsafe-fixesdemotes the named rules' safe fixes to unsafe. They then need--unsafe-fixes.
You can also turn on all unsafe fixes by default with unsafe-fixes = true under [tool.ruff], or pass --no-unsafe-fixes to override it on one run. Most teams keep the default and use --unsafe-fixes by hand together with --diff.
Command-line flags for automation
A few flags change how fixing reports its result:
| Flag | Effect |
|---|---|
| `--diff` | Print the changes as a diff and do not write files. |
| `--fix-only` | Apply fixes but do not print the remaining violations. |
| `--show-fixes` | Print a summary of which fixes were applied, grouped by file. |
| `--exit-non-zero-on-fix` | Exit with status 1 if any fix was applied, even when nothing remains. |
| `--unsafe-fixes` / `--no-unsafe-fixes` | Enable or disable unsafe fixes for this run. |
--exit-non-zero-on-fix matters for pre-commit. A hook that rewrites files should fail the commit, so you can review the changes and stage them. Without the flag, a fully repaired file exits with status 0 and the commit goes through with unstaged edits.
When there is no fix, or you do not want one
Some violations have no fix. For those, you have three options:
- Edit the code by hand.
- Suppress the violation with a
# noqacomment. A later chapter covers this. - Ask Ruff to write the
noqacomments for you withruff check --add-noqa. This is useful when you adopt Ruff on an old codebase and want a clean baseline, so that only new violations fail.
--add-noqa is not a fix in the sense of this chapter. It hides violations instead of removing them, so treat the added comments as a to-do list.
Fixing and formatting together
Fixes produce valid code, but not always code in your formatter's style. A removed import can leave extra blank lines, and a rewritten expression may use different spacing. Run the fixer first and the formatter second:
ruff check --fix .
ruff format .The formatter's output is stable and deterministic, so running it last gives you a consistent final state. Import sorting, covered in a later chapter, follows the same pattern with ruff check --select I --fix.
Common mistakes
- Expecting
--fixto fix everything. It skips unsafe fixes and rules with none. Read the summary line for hidden fixes. - Running
--unsafe-fixeswithout a diff or a clean working tree. You lose the ability to see what changed. - Setting
fix = truein a config that CI also uses. CI then modifies files in a throwaway checkout and passes. Useruff checkwithout fixing in CI, and keep fixing local. - Promoting rules with
extend-safe-fixestoo early. A rule that looks safe on your first file may not be on the hundredth. - Trusting a fix to be correct logic. The
if result is Nonebranch above shows that a rule can make dead code tidy without making it meaningful.
Exercise
You run ruff check --fix . on a project and Ruff exits with status 1. The output says one violation remains and that one fix was hidden. What are two different reasons the hidden fix was not applied, and how would you find out which one applies?
Show answer
The rule's fix is classified as unsafe, so it needs --unsafe-fixes, or the rule is listed in unfixable. To find out which, run ruff check --diff --unsafe-fixes . and see whether a diff appears for that violation. If a diff appears, the fix was unsafe and you can review and apply it. If no diff appears, check unfixable in [tool.ruff.lint]. A third possibility is that the rule is excluded from fixable and so cannot fix at all.
Exercise
Write the configuration that makes ruff check --fix apply fixes for every selected rule except the B rules, and that makes F401 fixes require --unsafe-fixes.
Show answer
Add this to pyproject.toml:
[tool.ruff.lint]
unfixable = ["B"]
extend-unsafe-fixes = ["F401"]
fixable defaults to all rules, so only unfixable needs to name B. extend-unsafe-fixes demotes the F401 fix from safe to unsafe.