Skip to main content

Dev tools and workflow · Intermediate · 22 min

Lint and format a Python project with Ruff

By Padding · Updated 18 Nov 2026
Python 3.15.2 · Ruff 0.17.6 · uv 0.13.10 · python:3.15-slim (Debian)

You will configure Ruff 0.17 for a small Python package, choose its rule sets in pyproject.toml, fix what it finds safely, format the code and finish with a project that passes ruff check and ruff format --check, ready for CI and your editor.

On this page

Ruff is a Python linter and formatter from Astral, written in Rust. One tool does the work of Flake8 and its plugins, isort, pyupgrade and Black. Write readable code: names, comments and a formatter runs Ruff on a single script. This tutorial sets it up the way a team project needs: settings committed in pyproject.toml, a rule list chosen on purpose, fixes you review before you accept them, exceptions that say why they exist, and two commands a CI job can run.

You build a small package called shopkit with a few order helpers and their tests. The first version has the kind of problems real code has: a mutable default argument that leaks state between calls, a bare except, a token written into the source, and old-style type hints. Ruff finds all of them, fixes some on its own, and leaves the rest for you. One of the tests fails at the start because of a bug Ruff reports, so you can watch a lint rule catch a real defect.

Ruff's wheel for Linux is about 11 MB. uv caches it, so on prepaid mobile data each machine downloads a given version once, and the lock file makes every teammate use that same version.

Step 1 · Create the project and pin Ruff

Create a throwaway project folder with a pyproject.toml. It declares the package and uses uv's own build backend, so shopkit can be imported by the tests:

Bash
mkdir -p ~/ruff-demo/src/shopkit ~/ruff-demo/tests
cd ~/ruff-demo
cat > pyproject.toml <<'EOF'
[project]
name = "shopkit"
version = "0.1.0"
requires-python = ">=3.15"

[build-system]
requires = ["uv_build>=0.13,<0.14"]
build-backend = "uv_build"
EOF
touch src/shopkit/__init__.py
uv add --dev "ruff==0.17.6" "pytest==9.2.0"

uv add --dev puts Ruff and pytest in a dev dependency group, so they are installed for development but are not requirements of the package itself. Pin Ruff to an exact version. Ruff's versioning policy allows a minor release to add or remove rules from the default set, change how a stable rule behaves and change the formatter's style. With an exact pin, an upgrade is a deliberate one-line change you can review, not a surprise on a Monday morning.

Check it worked

Bash
uv run ruff --version

It prints ruff 0.17.6. pyproject.toml now ends with a [dependency-groups] table listing both tools, and a uv.lock file sits next to it.

Step 2 · Write some code worth checking

Create the module. Read it once before you save it: several lines are wrong on purpose.

Bash
cat > src/shopkit/orders.py <<'PY'
import os, sys
import json
from typing import Dict, List, Optional

API_TOKEN = "not-a-real-token"


def order_total(prices: List[float], discount: Optional[float] = None) -> float:
    total = 0.0
    for price in prices:
        total = total + price
    if discount != None:
        total = total * (1 - discount)
    return round(total, 2)


def add_item(name: str, basket: List[str] = []) -> List[str]:
    basket.append(name)
    return basket


def load_order(text: str) -> Dict[str, object]:
    try:
        return json.loads(text)
    except:
        return {}


def receipt_line(name: str, amount: float) -> str:
    return "%s: %.2f" % (name, amount)


def pick_raffle_winner(customers: List[str]) -> str:
    import random
    return random.choice(customers)


def auth_header() -> Dict[str, str]:
    return {'Authorization':'Bearer '+API_TOKEN}
PY
cat > tests/test_orders.py <<'PY'
from shopkit.orders import receipt_line, add_item, order_total
import pytest


def test_total_with_discount():
    assert order_total([10.0, 5.0], discount=0.1) == 13.5


def test_baskets_start_empty():
    assert add_item("rice") == ["rice"]
    assert add_item("beans") == ["beans"]


def test_receipt_line():
    assert receipt_line("Tea", 2.5) == "Tea: 2.50"
PY
uv run pytest -q || echo "a test failed"

Check it worked

pytest ends with 1 failed, 2 passed. The failure is in test_baskets_start_empty: the second call returns ['rice', 'beans']. The default [] in add_item is created once, when Python defines the function, so every call that leaves out basket shares the same list. Keep this in mind; Ruff is about to point at it.

Step 3 · See what the default rules catch

Run the linter before you configure anything. --output-format concise prints one line per problem:

Bash
uv run ruff check --output-format concise || echo "ruff found problems"

ruff check exits with status 1 when it reports anything, so || echo prints a note instead of stopping your shell script.

With no [tool.ruff] settings, Ruff 0.17 uses its default rule set: several hundred rules chosen to catch likely bugs with few false alarms, drawn from Pyflakes (F), flake8-bugbear (B), pyupgrade (UP), isort (I) and many other groups. It reads requires-python from [project] to learn that the code targets Python 3.15, which is why it suggests list instead of typing.List.

Check it worked

The report ends with Found 17 errors. The list includes B006 Do not use mutable data structures for argument defaults, the bug behind the failing test, and E722 Do not use bare except. It does not mention the token in the source or the != None comparison. The defaults are a good start, but you cannot see from your own repository which rules apply, and an upgrade can change them.

Step 4 · Choose your rule sets in pyproject.toml

Add Ruff's settings to pyproject.toml. Settings under [tool.ruff] apply to the linter and the formatter; settings under [tool.ruff.lint] apply to the linter only:

Bash
cat >> pyproject.toml <<'EOF'

[tool.ruff]
target-version = "py315"
line-length = 88

[tool.ruff.lint]
select = ["E", "F", "I", "B", "UP", "S"]
EOF
uv run ruff check --output-format concise || echo "ruff found problems"

What each setting does:

  • target-version is the oldest Python the code must run on. Upgrade rules only suggest syntax that version supports. Ruff can also infer it from requires-python; when both are set, target-version wins. Writing it out keeps the linter's view visible even if someone loosens requires-python for packaging reasons.
  • line-length = 88 is Ruff's default, written down so nobody has to look it up. The formatter and the E501 line-length rule both use it.
  • select replaces the default rule set with the groups you name. Ruff's documentation recommends select over extend-select so the full rule set is visible in one place.

The six groups cover the problems most teams care about:

  • E: pycodestyle errors, such as comparing to None with != and several imports on one line.
  • F: Pyflakes, such as unused imports and undefined names.
  • I: import sorting, the job isort used to do.
  • B: flake8-bugbear, likely bugs such as mutable defaults.
  • UP: pyupgrade, older syntax that has a modern replacement for your target version.
  • S: flake8-bandit, security problems such as hard-coded secrets and assert used for checks.

Avoid select = ["ALL"]. It turns on every rule, including ones that contradict each other, and Ruff's documentation warns that it silently enables new rules whenever you upgrade. Start with a short list, get the code clean, then add one group at a time.

Check it worked

The report now ends with Found 25 errors. and a line saying 13 are fixable with --fix, with 3 unsafe fixes available with --fix --unsafe-fixes. New entries include E401 (two imports on one line), E711 (the != None), S105 Possible hardcoded password assigned to: "API_TOKEN", S311 (the random call) and four S101 Use of assert detected lines in the tests.

Step 5 · Apply safe fixes, then review the unsafe ones

Entries marked [*] have an automatic fix. Ruff sorts fixes into two kinds. Safe fixes keep the code's behaviour the same, and --fix applies only those:

Bash
uv run ruff check --fix --output-format concise || echo "ruff found problems"

Ruff splits the imports, removes the unused ones, sorts them and replaces List, Dict and Optional with list, dict and X | None.

Unsafe fixes might change behaviour or drop comments, so Ruff never applies them unless asked. Preview them first. --diff prints the changes without writing any file:

Bash
uv run ruff check --unsafe-fixes --diff || echo "fixes available"

Read each hunk. != None becomes is not None, which is right here. The percent format becomes an f-string, which gives the same text for these values. The mutable-default fix moves the empty list into the function body, which is what you want, but look at the signature it writes:

Text
def add_item(name: str, basket: list[str] = None) -> list[str]:

The default is now None while the annotation still says list[str]. The code runs, but a type checker such as mypy rejects it. This is why unsafe fixes need a person to read them. Apply them, and correct the annotation in the next step:

Bash
uv run ruff check --fix --unsafe-fixes --output-format concise || echo "ruff found problems"

Check it worked

The first --fix run ends with Found 25 errors (15 fixed, 10 remaining). The last run ends with 4 fixed, 7 remaining. These counts do not have to add up to the earlier 13 fixable and 3 unsafe: Ruff repeats its fix pass until nothing more changes, so one fix can make another possible, and a fix can clear more than one report. What is left has no automatic fix: S105, E722, S311 and the four S101 lines in the tests. The top of src/shopkit/orders.py is now:

Python
import json

API_TOKEN = "not-a-real-token"

Step 6 · Fix the rest by hand and record each exception

Three problems need a decision from you:

  • S105: the token is in the source, so it ends up in Git history and in every copy of the code. Read it from an environment variable when it is needed.
  • E722: a bare except also swallows KeyboardInterrupt and typos such as a misspelt name (NameError). Catch the one error you expect, json.JSONDecodeError.
  • S311: the random module is not safe for passwords or tokens. This function picks a weekly prize winner, which is not a security decision, so the warning does not apply. Keep the code and say so next to it.

Replace src/shopkit/orders.py with this version. It keeps Ruff's fixes, corrects the add_item annotation, moves the random import to the top and makes the three changes above. The auth_header line is left untidy on purpose for the formatter step:

Bash
cat > src/shopkit/orders.py <<'PY'
import json
import os
import random


def order_total(prices: list[float], discount: float | None = None) -> float:
    total = 0.0
    for price in prices:
        total = total + price
    if discount is not None:
        total = total * (1 - discount)
    return round(total, 2)


def add_item(name: str, basket: list[str] | None = None) -> list[str]:
    if basket is None:
        basket = []
    basket.append(name)
    return basket


def load_order(text: str) -> dict[str, object]:
    try:
        return json.loads(text)
    except json.JSONDecodeError:
        return {}


def receipt_line(name: str, amount: float) -> str:
    return f"{name}: {amount:.2f}"


def pick_raffle_winner(customers: list[str]) -> str:
    # A weekly prize draw, not a secret: the standard generator is fine here.
    return random.choice(customers)  # noqa: S311


def auth_header() -> dict[str, str]:
    token = os.environ['SHOPKIT_API_TOKEN']
    return {'Authorization':'Bearer '+token}
PY

# noqa: S311 silences that one rule on that one line. Always name the code: a bare # noqa hides every rule on the line, including problems added later. The comment above it tells a reviewer why the exception is there.

assert in application code is a real problem, because Python removes asserts when it runs with -O. In pytest tests, assert is how you write a check. Turn S101 off for the tests folder only, with a per-file ignore:

Bash
cat >> pyproject.toml <<'EOF'

[tool.ruff.lint.per-file-ignores]
"tests/**" = ["S101"]
EOF
uv run ruff check
uv run pytest -q

Prefer per-file-ignores to a list of noqa comments whenever a rule does not fit a whole group of files. Over time, a noqa can outlive the code it excused. uv run ruff check --extend-select RUF100 reports any noqa comment that no longer suppresses anything.

Check it worked

ruff check prints All checks passed! and pytest prints 3 passed. The test that failed at the start now passes, because each call to add_item gets its own list. Check that the token is read at call time:

Bash
SHOPKIT_API_TOKEN=demo-value uv run python -c "from shopkit.orders import auth_header; print(auth_header())"

It prints {'Authorization': 'Bearer demo-value'}. In a real project the variable comes from your shell profile, a .env file that Git ignores, or your deployment's secret store. It never goes into the code.

Step 7 · Format the code and set up your editor

The linter finds problems; the formatter decides layout: quotes, spaces, indentation and line breaks. See what it would change before you let it write:

Bash
uv run ruff format --diff || echo "files would be reformatted"
uv run ruff format
uv run ruff format --check

The diff shows two files. In orders.py, single quotes become double quotes and the operators in auth_header get spaces. In the tests file, the blank first line left behind when Ruff removed import pytest goes away.

Ruff's formatter is designed as a drop-in replacement for Black. Its documentation reports that on Black-formatted projects such as Django and Zulip, more than 99.9% of lines come out identical. A project moving from Black can switch with a diff of a few lines, and the same habits apply: double quotes by default, and a trailing comma after the last item of a list or call keeps it split one item per line. Ruff's documentation also lists a few lint rules that fight the formatter, such as COM812 (missing trailing comma) and E111 (indentation). Leave those out of select; the six groups here do not include them.

Most teams run the formatter on every save. In VS Code, install the Ruff extension (charliermarsh.ruff) from the Extensions view, then add workspace settings to the project:

Bash
mkdir -p .vscode
cat > .vscode/settings.json <<'EOF'
{
  "[python]": {
    "editor.defaultFormatter": "charliermarsh.ruff",
    "editor.formatOnSave": true,
    "editor.codeActionsOnSave": {
      "source.fixAll": "explicit",
      "source.organizeImports": "explicit"
    }
  }
}
EOF
python3 -m json.tool .vscode/settings.json > /dev/null && echo "settings are valid JSON"

On save, VS Code formats the file, applies safe fixes and sorts imports, using the same pyproject.toml settings as the command line. The extension uses the Ruff in your project's virtual environment when it finds one, so the editor and CI agree. Other editors, such as Neovim, Helix and Zed, talk to the same built-in language server, ruff server; the Ruff editor setup guide at docs.astral.sh has the configuration for each.

Check it worked

ruff format prints 2 files reformatted, 1 file left unchanged, and ruff format --check prints 3 files already formatted. The last line of orders.py now reads return {"Authorization": "Bearer " + token}. The JSON check prints settings are valid JSON. If you use VS Code, add an extra space inside any function call in orders.py and save: the space disappears.

Step 8 · Run the same checks in CI

A CI job must never change files; it fails when they need changing and shows why. These two commands do that. Each exits with status 1 when there is work to do:

Bash
uv run ruff check --output-format concise
uv run ruff format --diff

ruff check without --fix reports problems and changes nothing. ruff format --diff prints the changes the formatter would make, so whoever reads the failed job can see exactly what is wrong. ruff format --check gives the same pass or fail with a shorter message. Run both commands after uv sync --locked, so CI uses the Ruff version in uv.lock. On GitHub Actions, add --output-format github to ruff check and each problem shows up as an annotation on the pull request's changed lines; your first GitHub Actions workflow shows how to set up the job.

See the gate fail. Add a carelessly typed file and run the format check again:

Bash
printf 'def greet( name ):\n  return "hi "+name\n' > src/shopkit/scratch.py
uv run ruff format --diff || echo "CI would fail here"
rm src/shopkit/scratch.py

Check it worked

The first two commands print All checks passed! and 3 files already formatted, and both exit with status 0. The scratch file run prints a diff that adds spaces and four-space indentation, ends with 1 file would be reformatted, 3 files already formatted, and then prints CI would fail here. Your project is back to a clean state once the scratch file is removed.

Step 9 · Clean up

When you have finished experimenting, remove the demo project. Python and uv stay installed, and uv keeps the Ruff wheel in its cache for your next project:

Bash
cd ~
rm -rf ~/ruff-demo

Check it worked

ls ~/ruff-demo reports No such file or directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.