Skip to content

Lesson 3 of 59Your Python toolbox

Code Quality Tools

Lint and format with Ruff, catch bugs with mypy or pyright, and run every check automatically with pre-commit, your editor and CI.

16 min read0/4 questions

Open a pull request on a professional Python team and, before any human looks at it, a set of machines already has. A linter has flagged the unused import and the mutable default argument. A formatter has decided where every line breaks, so nobody argues about it. A type checker has noticed that find_user() can return None and you used .email on it anyway. This lesson sets up those three tools properly, explains the errors you will see most, and wires them into pre-commit, your editor and CI so they run without anyone remembering to.

Why teams enforce this

Each tool removes a whole category of review comments:

  • Formatting stops style debates and keeps diffs small. When every file is formatted the same way, a diff shows only the lines whose meaning changed.
  • Linting catches real bugs that tests often miss: an unused variable that should have been returned, a mutable default shared between calls, a bare except: that swallows KeyboardInterrupt.
  • Type checking catches the most common runtime crash in Python, calling something on a value that might be None or the wrong type, before the code runs.

The value comes from running them every time, automatically. A check that depends on someone remembering it is a check that gets skipped on Friday afternoon.

Ruff: linting and formatting in one tool

Ruff is a linter and formatter written in Rust. It reimplements hundreds of rules from older tools (flake8 and its plugins, isort, pyupgrade) and a formatter compatible with Black, and it checks a large codebase in well under a second. Add it as a dev dependency so everyone uses the same version:

uv add --dev ruffuv run ruff check .            # report problemsuv run ruff check --fix .      # apply safe automatic fixesuv run ruff format .           # reformat every fileuv run ruff format --check .   # CI: fail if anything would be reformatteduv run ruff rule B006          # explain a rule, with examples

Here is a typical first run on a small file:

app.py:1:1: I001 [*] Import block is un-sorted or un-formatted
app.py:1:8: F401 [*] `os` imported but unused
app.py:5:41: B006 Do not use mutable data structures for argument defaults
Found 3 errors.
[*] 2 fixable with `--fix`

Every rule has a code: a letter prefix for the family it came from and a number. [*] means Ruff can fix it automatically. Fixes it considers safe are applied by --fix. Fixes that might change behaviour are marked unsafe and only applied with --unsafe-fixes, after which you should read the diff.

Choosing rules

By default Ruff enables only a small, uncontroversial set (mostly E and F). Most teams opt into more in pyproject.toml:

pyproject.toml
[tool.ruff]
line-length = 100
target-version = "py312"
 
[tool.ruff.lint]
select = [
    "E", "W",   # pycodestyle: basic style errors
    "F",        # pyflakes: unused imports, undefined names
    "I",        # isort: import order
    "B",        # flake8-bugbear: likely bugs
    "UP",       # pyupgrade: modern syntax for your Python version
    "SIM",      # flake8-simplify: simpler equivalent code
    "S",        # flake8-bandit: security smells
    "RUF",      # Ruff's own rules
]
ignore = ["E501"]   # line length is the formatter's job
 
[tool.ruff.lint.per-file-ignores]
"tests/**" = ["S101"]   # assert is fine in tests

A few habits that keep this config healthy:

  • Add families gradually. Turning on 30 families on an old codebase produces thousands of errors and a team that ignores them. Add one family, fix or ignore what it finds, merge, repeat.
  • Prefer per-file-ignores to blanket ignores. assert is wrong in application code (it disappears under python -O) but it is how pytest works.
  • Suppress one line with a reason. import app.models # noqa: F401 (registers tables) tells the next reader why the rule does not apply. A bare # noqa with no code hides every future problem on that line too.
Match the pairs0/5 matched

Match each Ruff rule family to what it catches.

Choose an item, then its match on the other side.

How a linter works

A linter never runs your code. It parses the source into a syntax tree and walks it looking for patterns. Here is a two-rule linter using Python's own ast module:

Pythonmini_linter.py
import ast source = '''import osimport json def add_tag(tag, tags=[]): tags.append(tag) return json.dumps(tags)''' tree = ast.parse(source)imported = {}used = set() for node in ast.walk(tree): if isinstance(node, ast.Import): for alias in node.names: imported[alias.asname or alias.name] = node.lineno elif isinstance(node, ast.Name): used.add(node.id) elif isinstance(node, ast.FunctionDef): for default in node.args.defaults: if isinstance(default, (ast.List, ast.Dict, ast.Set)): print(f"line {node.lineno}: B006 mutable default in {node.name}()") for name, line in imported.items(): if name not in used: print(f"line {line}: F401 '{name}' imported but unused")
Output
Press Run (⌘ Enter) to see what happens.

Why is B006 a bug and not a style choice? The default list is created once, when the function is defined, and every call that omits tags shares it:

Predict the outputPython

What does this print?

def add_tag(tag, tags=[]):
  tags.append(tag)
  return tags

add_tag("a")
print(add_tag("b"))
Need a nudge? Hints walk you through it.

Type checking with mypy or pyright

Type hints do nothing at runtime. A type checker reads them and proves, without running anything, that the types line up. Two are widely used:

  • mypy is the original, with a plugin system (Pydantic and Django ship plugins) and a long track record.
  • pyright is faster and powers Pylance in VS Code, so its errors match what you see in the editor.

Either is a good choice. Pick one for CI so there is one source of truth.

uv add --dev mypyuv run mypy src

Strictness

By default mypy is lenient: functions without annotations are not checked at all, which is how it lets old code pass on day one. strict = true turns on everything, including "every function must be annotated" and "no implicit Any". New projects should start strict. Old projects should start lenient and tighten module by module:

pyproject.toml
[tool.mypy]
strict = true
plugins = ["pydantic.mypy"]
 
[[tool.mypy.overrides]]
module = "app.legacy.*"
ignore_errors = true        # tighten this later, one module at a time

The pyright equivalent is a [tool.pyright] section with typeCheckingMode = "strict" (or "standard").

The errors you will see most

app.py:20: error: Item "None" of "User | None" has no attribute "name"  [union-attr]
app.py:23: error: Function is missing a type annotation  [no-untyped-def]

The first is the one that saves you. find_user() returns User | None, and the code used .name without checking. The fix is to narrow the type:

app/services/greeting.py
def greet(user_id: int) -> str:
    user = find_user(user_id)
    if user is None:
        raise UserNotFound(user_id)
    return f"Hi {user.name}"          # the checker now knows user is a User

After if user is None: raise, the checker knows user cannot be None below. isinstance checks, early returns and match statements narrow the same way. Add reveal_type(user) on a line and the checker prints what it thinks the type is, which is the fastest way to understand a confusing error.

The second error comes from strict mode: annotate the function. A third common one, Incompatible return value type, usually means the function really does return two different things in different branches.

Sometimes you know more than the checker, for example about the shape of JSON you just validated. You have two escape hatches. typing.cast(User, value) tells the checker to treat a value as a type, without any runtime check. # type: ignore[union-attr] silences one specific error on one line. Always include the error code in brackets, so a different, new error on the same line is still reported, and treat every ignore as a small debt worth a comment explaining why.

Quick check
get_order() returns Order | None. Which version passes a strict type check?
Need a nudge? A hint rules out a wrong answer.

Third-party libraries

A type checker needs types for every library you import. There are three situations:

  1. The library ships its own types, marked by a py.typed file. FastAPI, Pydantic, SQLAlchemy 2.0, httpx and most modern libraries do. Nothing to do.
  2. Types live in a separate stubs package, usually named types-<name>. mypy says Library stubs not installed for "requests"; fix it with uv add --dev types-requests.
  3. No types exist. Silence it for that one module, not globally:
pyproject.toml
[[tool.mypy.overrides]]
module = ["legacy_sdk.*"]
ignore_missing_imports = true

Every value from an untyped library is Any, and Any switches checking off wherever it flows. Wrap such libraries in a small typed function of your own so Any stops at the edge of your code.

pre-commit: checks before every commit

pre-commit is a framework that installs a git hook. Every git commit runs your configured checks on the staged files, and the commit is blocked if any fail.

.pre-commit-config.yaml
repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.12.0                 # use the latest tag; `pre-commit autoupdate` bumps it
    hooks:
      - id: ruff-check
        args: [--fix]
      - id: ruff-format
  - repo: local
    hooks:
      - id: mypy
        name: mypy
        entry: uv run mypy src
        language: system
        types: [python]
        pass_filenames: false
uv tool install pre-commitpre-commit install               # once per clone: installs the git hookpre-commit run --all-files       # run everything now, e.g. after changing the config

Older configs use id: ruff instead of ruff-check; it still works as an alias. The mypy hook is a local hook that runs inside your project's environment, so it sees your real dependencies and their types. The popular mirrors-mypy hook runs mypy in an isolated environment that does not have your packages unless you list them again, which leads to confusing differences from CI.

Keep hooks fast. If the commit hook takes 30 seconds, people start committing with --no-verify, which skips all hooks. That is also why the hook is a convenience, not a guarantee.

Editor and CI: the full loop

The same checks at three moments
Editor: as you typeEditoras you typepre-commit: on git commitpre-commiton git commitCI: on every PRCIon every PRmain: protected branchmainprotected branchcommitpushmerge if green

The editor runs Ruff and the type checker live, with format on save. Problems are fixed seconds after you make them.

1/4

In the editor, install the Ruff extension and enable format on save, and set Pylance's type checking mode (or PyCharm's inspections) close to what CI enforces. All three layers read the same [tool.ruff] and [tool.mypy] sections from pyproject.toml, so they agree.

Put it in order5 steps

Order the steps for adding these tools to an existing project without stalling the team.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
linter
A tool that reads source code without running it and reports likely bugs and style problems.
formatter
A tool that rewrites code into one consistent layout, like ruff format.
rule code
An identifier like F401 or B006 naming one lint rule; the letters name the family.
type narrowing
Refining a type like User | None to User after a check such as if user is None: raise.
stub package
A types-<name> package that adds type information for a library that does not ship its own.
pre-commit
A framework that runs configured checks as a git hook before each commit.