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.
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 swallowsKeyboardInterrupt. - Type checking catches the most common runtime crash in Python, calling something on a value that might be
Noneor 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 examplesHere 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:
[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 testsA 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-ignoresto blanket ignores.assertis wrong in application code (it disappears underpython -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# noqawith no code hides every future problem on that line too.
Match each Ruff rule family to what it catches.
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:
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:
What does this print?
def add_tag(tag, tags=[]):
tags.append(tag)
return tags
add_tag("a")
print(add_tag("b"))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 srcStrictness
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:
[tool.mypy]
strict = true
plugins = ["pydantic.mypy"]
[[tool.mypy.overrides]]
module = "app.legacy.*"
ignore_errors = true # tighten this later, one module at a timeThe 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:
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 UserAfter 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.
get_order() returns Order | None. Which version passes a strict type check?Third-party libraries
A type checker needs types for every library you import. There are three situations:
- The library ships its own types, marked by a
py.typedfile. FastAPI, Pydantic, SQLAlchemy 2.0, httpx and most modern libraries do. Nothing to do. - Types live in a separate stubs package, usually named
types-<name>. mypy saysLibrary stubs not installed for "requests"; fix it withuv add --dev types-requests. - No types exist. Silence it for that one module, not globally:
[[tool.mypy.overrides]]
module = ["legacy_sdk.*"]
ignore_missing_imports = trueEvery 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.
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: falseuv 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 configOlder 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 editor runs Ruff and the type checker live, with format on save. Problems are fixed seconds after you make them.
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.
Order the steps for adding these tools to an existing project without stalling the team.
- Tap the steps below in the right order.
- 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
F401orB006naming one lint rule; the letters name the family. - type narrowing
- Refining a type like
User | NonetoUserafter a check such asif 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.