Linting and Formatting with Ruff
Ruff is a linter and a formatter in one tool. ruff check finds likely mistakes such as unused imports and misspelled names before the code runs, and ruff format lays out every file the same way, with its settings in pyproject.toml and its checks in VS Code as you type.
Journeyman · Python · Software Development · Updated
After this lesson you can
- Run ruff check to find mistakes such as unused imports and undefined names, and fix them by hand or with --fix
- Format code with ruff format, keep Ruff's settings in pyproject.toml, and let VS Code format each file on save
Key takeaways
- A linter reads code without running it and points out likely mistakes. ruff check reports unused imports, names that were never defined and other slips, each with its line.
- ruff check --fix makes the fixes Ruff is sure of, such as removing an unused import, and leaves the rest for you to fix by hand.
- A formatter rewrites a file's layout (spaces, quotes, blank lines) without changing what the code does. ruff format does it in the style of PEP 8, Python's style guide.
- A project keeps Ruff's settings in pyproject.toml, and VS Code's Ruff extension shows its findings as you type and can format each file when you save.
Open any Python project on GitHub and you'll find a linter and a formatter in its settings, and many class projects are graded on tidy code as well as working code. Both tools do the same favor for you: they catch the small slips and settle the small arguments, so you and the people who read your code can spend your attention on what the code does.
The example is Peak Fitness, a gym whose front desk greets each member when they check in.
Two kinds of messy
Three people have worked on the gym's check-in script, and it shows:
import random
def checkin_message(name,visits):
if visits>=100:
return f"Welcome back, {name}! Visit {visits}: you joined the 100 Club."
return f"Welcome back, {nmae}! Visit {visits}."
print(checkin_message( "Rosa",100 ))
print(checkin_message("Dev",12))
It has two kinds of problem. The first kind is mistakes: random is imported and never used, and nmae is a typo for name. Run it and Rosa's line prints, because she's on her 100th visit; Dev's call reaches the typo and stops with NameError: name 'nmae' is not defined. A member with fewer than 100 visits is most members, so the first person to find this bug would be the person at the front desk.
The second kind is layout: a space after one comma and not another, spaces inside some parentheses. Nothing breaks, but every reader slows down, and three people's habits turn every change into an argument about spaces. Python has a style guide for this, PEP 8 (read "pep eight"), that most Python code follows.
Ruff handles both. Install it in the project's virtual environment:
pip install ruff==0.17.5
Finding mistakes with ruff check
A linter is a spell checker for code: it reads the code without running it and underlines what looks wrong. ruff check . runs Ruff's linter on every Python file in the folder:
ruff check .
F401 [*] `random` imported but unused
--> checkin.py:1:8
|
1 | import random
| ^^^^^^
help: Remove unused import: `random`
|
- import random
1 |
|
F821 Undefined name `nmae`
--> checkin.py:7:29
|
5 | if visits>=100:
6 | return f"Welcome back, {name}! Visit {visits}: you joined the 100 Club."
7 | return f"Welcome back, {nmae}! Visit {visits}."
| ^^^^
Found 2 errors.
[*] 1 fixable with `--fix`.
Each finding starts with a rule code and what's wrong. F401 is an unused import; F821 is an undefined name, the NameError that Dev would have hit, found before anyone ran the code. The arrow line gives the file, the line and the column, checkin.py:7:29, and the lines under it show the spot with ^^^^.
[*] marks a finding Ruff knows how to fix by itself. --fix makes those fixes:
ruff check --fix .
F821 Undefined name `nmae`
--> checkin.py:6:29
|
4 | if visits>=100:
5 | return f"Welcome back, {name}! Visit {visits}: you joined the 100 Club."
6 | return f"Welcome back, {nmae}! Visit {visits}."
| ^^^^
Found 2 errors (1 fixed, 1 remaining).
The import is gone, so the typo is on line 6 now. Ruff won't guess what nmae should be, so that one is yours: change it to name, run ruff check . again, and it answers All checks passed!.
One layout with ruff format
A formatter rewrites a file's layout, its spaces, quotes, blank lines and line breaks, without changing what the code does. ruff format . formats every Python file in the folder:
ruff format .
1 file reformatted
def checkin_message(name, visits):
if visits >= 100:
return f"Welcome back, {name}! Visit {visits}: you joined the 100 Club."
return f"Welcome back, {name}! Visit {visits}."
print(checkin_message("Rosa", 100))
print(checkin_message("Dev", 12))
Welcome back, Rosa! Visit 100: you joined the 100 Club.
Welcome back, Dev! Visit 12.
One space after each comma, spaces around >=, none inside the parentheses, two blank lines around the function: the PEP 8 way. You never argue about layout again, because nobody chooses it.
ruff format --check . asks the same question without changing anything. It lists the files it would reformat and ends with 1 file would be reformatted, or says 1 file already formatted. Tests and graders run that one, since they shouldn't change your files.
Settings, and Ruff in VS Code
Ruff reads its settings from pyproject.toml, the project's settings file, in the project's folder:
[tool.ruff]
line-length = 100
[tool.ruff.lint]
select = ["E", "F", "I"]
line-length is the longest a line may be before ruff format breaks it and ruff check reports it (88 characters unless you say otherwise). select picks the rule families ruff check uses: E for PEP 8's layout rules, F for likely mistakes (F401 and F821 are two of them) and I for imports in a tidy order. Without a select line, Ruff uses its own default set of rules; naming the families means everyone on the project gets the same ones.
In VS Code, install Ruff by Astral from the Extensions view. It underlines each finding as you type, with the same rule codes:
To format each file when you save it, open the Command Palette (Ctrl+Shift+P, or Cmd+Shift+P on a Mac), choose Preferences: Open User Settings (JSON), and add these lines inside the outer braces:
"[python]": {
"editor.defaultFormatter": "charliermarsh.ruff",
"editor.formatOnSave": true
}
[python] limits the settings to Python files, editor.defaultFormatter names Ruff's extension, and editor.formatOnSave runs it on every save.
Check yourself
2 questions to try on the lesson page.
So what
A linter catches the slip that would have stopped the program for most members, and a formatter ends the arguments about spaces, so the only thing left to talk about in your code is what it does.