Skip to content
Anthony Velez Tapia

Strict Python: the tools that warn you before production

I come from .NET. There, if you call a method with the wrong type, the project does not compile and you find out before running anything. Not in Python: the code starts, and the error shows up when that line runs, sometimes in production.

Python accepts type annotations, but does not check them: at runtime, it ignores them. It is the same as TypeScript, whose types disappear when it becomes JavaScript. The difference is that in TypeScript the compiler checks them first; in Python you have to build that compiler yourself.

And the compiler is only the first safety net. You need others for the logic, for the dependencies, for the package you publish and for every system it will run on. This is the list of the ones I use, plus a few more worth knowing.

Here I explain how I set it up in Django Cotton Gallery, a Django library with its source code public on GitHub. The examples come from its repository, with a link to each file: which tool provides each piece, which error it catches and when it runs.

Doesn’t Python compile?

It does, but to bytecode, the instructions its interpreter then runs. That step does not check types or whether a function exists: it only translates. That is why a type error does not show until the line runs.

1. The base: a single configuration file

The whole project is described in one pyproject.toml: dependencies, Python version and the configuration of every tool.

For the environment, the classic way is venv and pip, which ship with Python: python -m venv .venv creates the virtual environment and pip install -e . installs the project into it. It works, but pip does not record the exact versions it installs: everyone pins them their own way, with a requirements.txt or with another tool.

uv does the same and more: it creates the environment, installs the dependencies much faster, downloads the Python version you ask for and records the exact versions in uv.lock. Whoever clones the repository gets exactly what you have.

With venv and pip With uv
python -m venv .venv uv venv
pip install -e ".[test]" uv pip install -e ".[test]" or uv sync
Exact versions: by hand (pip freeze > requirements.txt) uv.lock, automatic
Python: whichever you have installed uv python install 3.12

Two structural details that help later:

  • The code lives in src/, apart from the repository root. That way nothing accidentally imports a loose file at the root that is not part of the package.
  • An empty py.typed file inside the package (Django Cotton Gallery’s) tells whoever uses it that it ships types. Without it, their type checker ignores yours.

2. Ruff: style and silly mistakes

Ruff does two jobs: it formats the code so everything has the same style, and it checks rules that point out common mistakes. It is very fast, and it replaces several tools that used to run separately (flake8, isort, pyupgrade…).

Each family of rules is turned on by its prefix. These are the ones Django Cotton Gallery turns on in its pyproject.toml:

[tool.ruff.lint]
select = [
    "E", "W",  # style (pycodestyle)
    "F",       # logic errors: unused imports or variables (pyflakes)
    "I",       # import order
    "B",       # common traps (bugbear)
    "UP",      # modern syntax for your Python version
    "SIM",     # code that can be simplified
    "C4",      # better-written comprehensions
    "DJ",      # Django good practices
    "RUF",     # Ruff's own rules
]

A generic example of what B catches: a list as a default value. Python creates it only once, so every call shares the same list:

def add_tag(tag, tags=[]):  # B006: mutable default argument
    tags.append(tag)
    return tags

It works on your first try and fails on the second. Ruff flags it without running anything.

assert statements are a case of their own. Python removes them when it runs with -O, so they are no good for checking anything important in application code. If you want Ruff to flag every assert in your code, turn on rule S101 and turn it off in the tests, where pytest needs them. If not, add neither:

[tool.ruff.lint]
extend-select = ["S101"]

[tool.ruff.lint.per-file-ignores]
"tests/**" = ["S101"]

In depth: Ruff: which rules to turn on, and how not to end up with three versions.

3. mypy in strict mode: the missing compiler

mypy reads the annotations and checks that the code respects them. It is the closest thing to the .NET compiler. With strict = true it stops being nice:

  • every function must have its types annotated;
  • you cannot return an untyped value (Any) where you promise a concrete one;
  • it flags impossible comparisons and # type: ignore comments that are no longer needed.

The typical case is a value that can be None (another generic example):

def find_component(name: str) -> Component | None: ...

component = find_component("button")
component.render()  # error: Item "None" of "Component | None" has no attribute "render"

At runtime, this only fails the day the component does not exist. mypy makes you decide what happens in that case before it happens.

With Django you need django-stubs, which teaches mypy Django’s types: models, QuerySet, requests. And strict mode can be relaxed where it does not pay off. In Django Cotton Gallery, the templatetags receive internal objects from the template engine without useful types, so I turn it off for that module instead of filling it with Any (pyproject.toml):

[tool.mypy]
strict = true
plugins = ["mypy_django_plugin.main"]

[[tool.mypy.overrides]]
module = "django_cotton_gallery.templatetags.*"
disallow_untyped_defs = false
mypy or Pyright?

Pyright does the same, and it is the engine VS Code (Pylance) uses to underline errors while you type. Which one is faster? It depends on whether mypy has its cache: it stores what it already checked in .mypy_cache and on the next run only looks at what changed. Pyright keeps nothing between runs. Measured on Django Cotton Gallery:

First run Next runs
mypy 5.2 s 1.0 s
Pyright 2.5 s 2.5–2.9 s

On your machine, with the cache already built, mypy wins. In CI, which starts from scratch, Pyright wins, unless you keep the .mypy_cache folder between runs.

And you do not have to choose. In SnakeORM, an ORM, both run on the same code, because the ORM promises to work with either of them (pyproject.toml).

In a Django project, mypy also has the Django plugin, which understands things like a model’s fields. That is why the CI of Django Cotton Gallery uses mypy (lint.yml).

In depth: mypy and Pyright in strict mode and the typed Django ORM.

Type tests: making the types say what they promise

If your code is a typed API, like an ORM, the types are tested too. In SnakeORM there are two files that never run; only mypy and Pyright read them:

  • cases_positive.py pins down with assert_type which type the checker must infer. If a change makes a query return Any instead of list[Nomina], it fails.
  • cases_negative.py contains errors on purpose, each one marked with the error it must produce:
truck = Truck(id=1, model="Ibiza", maker_id=1)
truck.no_declarada  # EXPECT: attr-defined
model: str = truck.id  # EXPECT: assignment

A test runs both checkers on those files and requires them to error exactly on those lines. If one day the code stops rejecting truck.no_declarada, the typing has opened a hole and the test says so.

In depth: Type tests.

4. Tests: from the known cases to the ones you would never think of

Types do not tell you whether the code does the right thing. That is what tests are for, with pytest and three add-ons:

  • pytest-django to test views and templates.
  • Hypothesis for the cases you would never think of. Instead of writing the inputs yourself, you describe what they look like and Hypothesis generates hundreds.
  • Playwright to test the page in a real browser.

My best example is in another project, SnakeORM, an ORM. The property is simple: any value you save to the database must come back identical when you read it. Instead of me picking a few values, the test asks Hypothesis for dozens per type, on Postgres and on SQLite: integers at the 64-bit edges, text with any character, dates with microseconds, long decimals.

The interesting part is how the inputs are bounded:

_INTEGERS = st.integers(min_value=-(2**63), max_value=2**63 - 1)
_TEXTS = st.text(alphabet=st.characters(codec="utf-8", exclude_characters="\x00"))
_FLOATS = st.floats(allow_nan=False, allow_infinity=False)

Each exclusion has its reason: a NaN cannot come back identical because NaN != NaN, and the null character (\x00) does not fit in a text column in any database. Bounding inputs to what the contract promises is fine; excluding something without a reason would be hiding a bug.

If Hypothesis finds a value that breaks it, it shrinks it to the shortest possible example before showing it to you.

In depth: pytest: from fixtures to tests that fail now and then.

Coverage: which code nobody tests

pytest-cov measures which lines the tests run. In Django Cotton Gallery it also measures branches (branch = true in its pyproject.toml): going through an if is not enough, you have to go through both the yes and the no. CI uploads the report to Codecov from a single combination of the matrix (test.yml).

Mutation testing: do your tests test anything?

100 % coverage only says the tests go through the code, not that they check what it does. Mutation testing measures it the other way round: it changes the code on purpose (a > for a >=, a True for a False) and checks whether some test fails. If none fails, that change, that “mutant”, survives, and you have found a gap in your tests.

In Python, the tool is mutmut, which works with pytest. I do not use it in these projects yet, but I do use the same principle with Stryker in @velezanthony/design, my documentation library, which is TypeScript: the tool changes, the idea is the same.

In depth: Mutation testing: the test that tests your tests.

5. Dependencies: the code you do not write

A good share of the code running in production is not yours. Three tools keep an eye on it:

  • Dependabot opens a PR whenever a new version of a dependency comes out. In Django Cotton Gallery it checks the Python dependencies and the CI actions every week (dependabot.yml). Since every PR goes through CI, you know whether the update breaks anything before accepting it.
  • deptry compares what your code imports with what your pyproject.toml declares: it flags a dependency you use without declaring it (it works on your machine because you installed it some other way) and one you declare but no longer use.
  • pip-audit looks up your dependencies in the databases of known vulnerabilities.

6. The matrix: every version and three systems

A library does not only run on your machine. Django Cotton Gallery supports Python 3.10 to 3.13 and Django 4.2 to 6.0, and the combinations have to be tested. I do it in two places.

Locally, with tox. It creates an isolated environment per combination and runs the tests in each one. One line in its tox.ini describes the whole matrix:

[tox]
envlist =
    py310-django{42,50,51,52}
    py311-django{42,50,51,52}
    py312-django{42,50,51,52,60}
    py313-django{51,52,60}

On GitHub Actions, with a matrix (test.yml). The same combinations on Linux and, on top, a few on Windows and macOS: not all of them, which would be over 50 jobs, but Python 3.12 with the long-term-support versions of Django.

Those few have already earned their place. A page of Django Cotton Gallery showed the path of the components folder with str(path), which on Windows uses backslashes (C:\…\templates\cotton). In the first PR, every Linux and macOS job passed and only the two Windows ones failed (Django 4.2 and Django 5.2). The fix was to change str(path) to path.as_posix(), which uses / on every system. Without Windows in the matrix, a user would have found it.

In depth: The CI matrix: what only fails on another version or another system.

7. The package: check it before publishing

If you publish to PyPI, the package can also come out broken: a missing file, metadata PyPI rejects. In Django Cotton Gallery, the release workflow (release.yml) builds the package with python -m build and validates it with twine check before uploading it.

The project itself has an example of why it matters. Version 1.32 of hatchling, the tool that builds the package, generates metadata in a newer format than twine accepts. That is why the pyproject.toml caps it at hatchling<1.32, with a comment explaining why.

8. Everything passing before each commit

If the checks only run in CI, you find out late. With pre-commit (its configuration), Ruff runs on every git commit and fixes what it can before the change is saved. And so you do not have to remember commands, a Makefile with one per task:

Command What it does
make lint Ruff checks the code
make typecheck mypy in strict mode
make test the tests on your Python version
make matrix tox with every combination

A lesson from here: the hook and CI versions must match. In a PR of Django Cotton Gallery, the pre-commit hook used Ruff 0.15.12 and CI used 0.15.20. Locally the code passed formatting, but in CI the “Check formatting” step failed. I fixed it by reformatting with the CI version and bumping the hook’s, which now carries a comment to keep them in sync.

Others worth knowing

I do not use them in these projects, but they solve problems you will run into eventually:

  • import-linter enforces architecture rules: for example, that the domain layer imports nothing from the web layer.
  • nox does the same as tox, but its configuration is written in Python instead of an .ini file.

Summary

Layer Tool What it catches When
Environment uv “it works on my machine” on install
Style and traps Ruff mutable default arguments, unused imports on every commit and in CI
Types strict mypy and Pyright unexpected None, types that do not fit in the editor and in CI
Type contract type tests types that stop rejecting wrong code in CI
Behaviour pytest, Hypothesis, Playwright broken logic, odd inputs, the page in the browser locally and in CI
Test quality coverage and mutation testing untested code, tests that check nothing in CI
Dependencies Dependabot, deptry, pip-audit old versions, undeclared dependencies, vulnerabilities weekly and in CI
Compatibility tox and the CI matrix Python and Django versions, Windows and macOS locally and in CI
Package build and twine check a package PyPI rejects on release

No layer replaces the others. Together they do what the compiler did in .NET, and quite a bit more.

References