Linting & formatting with Ruff
Keep code consistent automatically with a linter and formatter.
By Invicly Tech, , in Python Programming from Zero. About 10 minutes to read.
In short
A formatter rewrites code into one consistent style, and a linter flags likely bugs and bad habits. Ruff does both very fast, so style debates disappear and small mistakes get caught automatically.
Explained simply
Code is read far more often than it is written. When every file uses the same spacing, quotes and line breaks, your eyes can focus on what the code does instead of how it looks. A formatter is a tool that rewrites your files into one standard style automatically.
A linter is a different tool. It reads your code without running it and points out likely mistakes: an import you never use, a variable you assign and forget, a name that does not exist, a comparison that should use is. Many of these are real bugs waiting to happen.
Ruff does both jobs and is extremely fast, so it can check a whole project in a fraction of a second. It replaces several older tools (such as Flake8, isort and Black) with one install and one config section.
Once it is set up, you hardly think about it. Your editor formats the file every time you save, and fixes simple problems for you. The style debates in code review disappear, because the tool decides.
Press Play on a diagram to walk through it one step at a time.
- 1Write code
Focus on logic, not spacing
- 2ruff format .
Rewrites layout, quotes and line breaks
- 3ruff check .
Reports unused imports, undefined names and more
- 4ruff check --fix
Auto-fixes the safe issues
- 5Commit clean code
Optionally enforced by CI or a pre-commit hook
- Changes how code looks
- Spacing, quotes, line breaks
- Never changes behaviour
- No warnings, just rewrites
- Finds likely bugs and bad patterns
- Reports rule codes like F401
- Some issues auto-fixable
- Configured with select and ignore
In depth
What a linter actually finds
Each Ruff rule has a code. The letter prefix says which family it comes from. F rules come from Pyflakes and catch real errors: F401 an unused import, F841 a local variable that is assigned but never used, F821 an undefined name (often a typo). E and W rules come from pycodestyle and cover style, like E711 for == None instead of is None. I rules sort imports, B rules (from flake8-bugbear) catch bug patterns like B006, a mutable default argument such as def f(items=[]), and UP rules upgrade old syntax to modern Python.
Out of the box, Ruff enables only a safe core: the F rules plus the E4, E7 and E9 groups. Add more families with select. Run ruff rule F401 to read a full explanation of any rule, with examples.
- F401 unused import, F841 unused variable, F821 undefined name
- E711: use is None, not == None
- B006: mutable default argument
- I001: imports are not sorted
How ruff format decides the style
ruff format is designed to produce the same output as Black, the most widely used Python formatter. Defaults: lines up to 88 characters, double quotes, four-space indents, and spaces around operators. When a call is too long, it is split one argument per line. If you add a trailing comma after the last item yourself (the magic trailing comma), the formatter keeps the list exploded, one item per line, even if it would fit.
Formatting never changes what code does, and it does not remove unused imports: that is the linter's job. In CI, run ruff format --check . to fail if any file is not formatted, or ruff format --diff . to see the changes without writing them. For a hand-aligned table you want to keep, wrap it in # fmt: off and # fmt: on comments.
Fixing automatically, and safely
ruff check --fix applies the fixes Ruff marks as safe, meaning they keep the code's behaviour, like removing an unused import or sorting imports. Some fixes are unsafe, because they might change behaviour, for example deleting an unused variable whose right-hand side calls a function. Those are applied only with --unsafe-fixes, so review the diff when you use it. --diff previews fixes without changing files.
When a warning is wrong for one line, silence just that rule on that line with a comment like # noqa: F401, and never a bare # noqa that hides everything. For whole groups of files, use per-file-ignores in the config, for example allowing unused imports in __init__.py files that re-export names. ruff check --watch reruns on every save if you like working in the terminal.
- Remove unused import
- Sort imports
- Upgrade old syntax
- Behaviour is unchanged
- Delete an unused variable
- Might drop a side effect
- Review the diff first
- Off by default
Configuring Ruff in pyproject.toml
Settings live under [tool.ruff] in pyproject.toml (or in a ruff.toml file, without the tool.ruff prefix). Top-level options apply to both tools: line-length = 100 and target-version = "py312", which tells Ruff which Python syntax it may assume. Linter options go under [tool.ruff.lint]: select lists rule families to enable, ignore removes single rules, and [tool.ruff.lint.per-file-ignores] tunes rules by path. Formatter options go under [tool.ruff.format], such as quote-style = "single".
A good starting set for a new project is select = ["E", "F", "I", "B", "UP"]. Turn on more only when you understand what each family checks, otherwise the warnings become noise that everyone learns to ignore.
Running it everywhere, automatically
Tools only help if they run every time. In VS Code, install the Ruff extension (charliermarsh.ruff), set it as the default Python formatter, and turn on format on save; codeActionsOnSave with source.fixAll and source.organizeImports applies safe fixes and sorts imports on save too.
A second safety net is a Git pre-commit hook. The pre-commit framework with the official ruff-pre-commit hooks runs Ruff on the changed files before each commit. The final net is CI: run ruff check . and ruff format --check . on every push, so unformatted or failing code cannot be merged. Pin the Ruff version in your requirements so everyone gets identical results, because new versions can add rules or change formatting slightly.
- Step 1Editor on save
Formats and fixes as you work
- Step 2pre-commit hook
Checks changed files before each commit
- Step 3CI on push
ruff check . and ruff format --check .
- Step 4Merge allowed
Only clean code reaches main
Learn it in 3 short steps
About 20m each. Track them with a timer in your plan.
- 1Install and run Ruff~20m
- 2Auto-format code with ruff format~20m
- 3Fix lint warnings automatically~20m
Key points
- Install with pip install ruff inside your venv.
- ruff format handles style; ruff check finds problems.
- Configure rules and line length under [tool.ruff] in pyproject.toml.
- Run Ruff on save in VS Code so issues appear as you type.
Key terms
Tap a card to flip it. 0/5 known
Examples
pip install ruff
ruff format . # reformat every file
ruff check . # list problems
ruff check --fix . # fix what can be fixed safely
# pyproject.toml
# [tool.ruff]
# line-length = 100
# [tool.ruff.lint]
# select = ["E", "F", "I"]What Ruff finds in a small file
Step 1: run ruff check app.py with the default rules. Step 2: read the findings: two unused imports on one line, an unused variable, and a None comparison. Step 3: ruff check --fix removes the unused imports, which is safe. Step 4: enable the B family and Ruff also flags items=[], the shared mutable default bug from the functions topic. The other two need a small manual edit.
# app.py
import os, sys
def add_item(item, items=[]):
unused = 1
if item == None:
return items
items.append(item)
return items
# ruff check app.py (default rules) reports:
# E401 multiple imports on one line F401 os, sys imported but unused
# F841 local variable never used E711 comparison to None
# with select = ["E", "F", "B"] it also reports:
# B006 mutable default argument items=[]A project configuration and a CI check
Step 1: add the config to pyproject.toml: a 100-character limit, Python 3.12 syntax, and a useful rule set. Step 2: let the formatter handle long lines, so E501 (line too long) is ignored. Step 3: allow unused imports in __init__.py, where they re-export names. Step 4: in CI, run both commands; either one fails the build if something is wrong.
[tool.ruff]
line-length = 100
target-version = "py312"
[tool.ruff.lint]
select = ["E", "F", "I", "B", "UP"]
ignore = ["E501"]
[tool.ruff.lint.per-file-ignores]
"__init__.py" = ["F401"]
# CI steps:
# ruff check .
# ruff format --check .Quick reference
- pip install ruff; then ruff format . and ruff check .
- ruff check --fix applies safe fixes; --unsafe-fixes only after reviewing
- ruff format --check . fails CI if any file needs formatting
- ruff rule F401 explains a rule with examples
- # noqa: F401 silences one rule on one line; avoid bare # noqa
- Good starter: select = ["E", "F", "I", "B", "UP"] under [tool.ruff.lint]
- Default line length is 88; set line-length under [tool.ruff]
Common mistakes
- Ignoring warnings like unused variables that often hide real bugs.
- Mixing two formatters with conflicting rules.
- Reformatting a whole old project in a commit with other changes.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Install Ruff in your venv, write a messy file with odd spacing and single quotes, run ruff format on it, and compare before and after.
- Exercise 2medium
Turn on import sorting and bugbear rules for your project, fix everything safe automatically, and list what is left.
- Exercise 3hard
Make Ruff format and fix on save in VS Code, and make CI fail when code is unformatted or has lint errors.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Do I still need Black or Flake8 if I use Ruff?
- Usually not. ruff format is designed to match Black, and ruff check covers Flake8, isort and many plugins. Running both formatters would only fight each other.
- Is Ruff a type checker?
- No. Ruff checks style and common mistakes; it does not verify types. Use mypy or Pyright alongside it.
- Should I reformat an old project in one go?
- Yes, but in a separate commit that contains only formatting, so the history of real changes stays readable. Git can skip that commit in blame using a .git-blame-ignore-revs file.
- What line length should I use?
- 88 is the default and works well. Many teams use 100 or 120; pick one and put it in the config so everyone and every tool agrees.