Typing, testing & tooling
Type hints, pytest, linters/formatters and sane project structure.
Type hints and static checking with mypy
Type hints document intent and let a separate tool catch mismatches before the code ever runs.
Writing def total(prices: list[float]) -> float: documents the expected argument and return types, but the interpreter itself never checks or enforces them at runtime. That does not make annotations purely a static-checker convenience, though: they are real metadata that some runtime libraries inspect and act on directly (dataclasses reading field types, or a framework validating request data), and since Python 3.14 they are evaluated lazily by default rather than eagerly, with the annotationlib module providing reliable ways to inspect or resolve them. For most application code, the biggest day-to-day value still comes from running a separate static type checker like mypy over the codebase, which reads the hints and the code paths it can statically analyze to flag inconsistencies — like passing a str where a float was declared — before the code is ever executed, within its configured strictness and the limits of what it can actually infer; it is not a proof that every runtime path is type-safe. X | None (Python 3.10+) marks a value as optional, and list[str], dict[str, int] express generic container contents directly using the built-in types.
Key points
- The interpreter never enforces type hints at runtime, but they are also real metadata some libraries read, and evaluated lazily by default since 3.14
- mypy (or pyright) reports inconsistencies it can statically detect — not proof every runtime path is type-safe
- X | None marks optional values; list[str]/dict[str, int] express generic container contents
Code
Run the code to see the result.
A fully type-hinted function; a static checker (not the interpreter) would catch a wrong-typed call.
Common pitfalls
- Believing type hints prevent runtime errors — they only help if a checker is actually run, e.g. in CI
- Forgetting -> None on a function that has no meaningful return value is a common inconsistency mypy flags
Practice exercise
Add complete type hints to a small function of your choice, install mypy, and run it against the file to see what, if anything, it flags.
Writing tests with pytest
plain assert statements, test discovery by naming convention, and fixtures for shared setup.
pytest discovers any function named test_* inside a file named test_*.py (or *_test.py) automatically, with no registration needed, and a plain assert expression is enough to make a test fail with a detailed, automatically-generated explanation of what went wrong — no special assertion methods required. @pytest.fixture defines reusable setup (and, after a yield, teardown) that any test can request simply by naming it as a parameter, and @pytest.mark.parametrize runs the same test body once per given set of inputs, reporting each as an independent pass/fail result.
Key points
- test_.py files with test_ functions are discovered automatically, no registration needed
- Plain assert is enough; pytest generates a detailed failure explanation automatically
- @pytest.fixture provides reusable setup/teardown; @pytest.mark.parametrize runs one test per input set
Code
# test_math_utils.py
import pytest
from math_utils import divide
@pytest.mark.parametrize("a,b,expected", [(10, 2, 5), (9, 3, 3)])
def test_divide(a, b, expected):
assert divide(a, b) == expected
def test_divide_by_zero_raises():
with pytest.raises(ZeroDivisionError):
divide(1, 0)A parametrized test covering multiple input combinations, plus a test that asserts an exception is raised.
Common pitfalls
- Test functions not prefixed with test_ are silently skipped by pytest's discovery
- Forgetting pytest.raises(...) around code expected to fail means the test only passes if it does NOT raise, the opposite of the intent
Practice exercise
Write parametrized pytest tests for the is_palindrome(text) function from an earlier lesson, covering an empty string, a single character, and a mixed-case palindrome.
Linters and formatters in a normal workflow
A formatter enforces one consistent style automatically; a linter catches likely bugs and style violations.
A formatter like black or ruff format rewrites code into one deterministic style — spacing, line breaks, quote style — removing style debates from code review entirely, since the tool decides and everyone's code ends up looking the same. A linter like ruff or flake8 instead analyzes code for likely bugs (an unused import, a variable that shadows a built-in, a comparison that is always false) and PEP 8 style violations, without changing the code itself. Running both automatically before every commit, via a pre-commit hook or CI check, keeps a codebase consistently clean without relying on manual review to catch every issue.
Key points
- A formatter (black, ruff format) rewrites code into one deterministic style automatically
- A linter (ruff, flake8) flags likely bugs and style violations without changing code
- Running both automatically in CI or a pre-commit hook keeps a codebase consistently clean
Code
# pyproject.toml
[tool.ruff]
line-length = 100
[tool.ruff.lint]
select = ["E", "F", "I"]
# command line
ruff format .
ruff check .Configuring ruff in pyproject.toml, then formatting and linting the whole project from the command line.
Common pitfalls
- Ignoring a linter warning by disabling the whole rule project-wide instead of fixing the specific case hides real future bugs
- Running a formatter without a CI check to enforce it means unformatted code can still be committed by mistake
Practice exercise
Install ruff, run ruff check . on a small existing script of yours, and fix the first three issues it reports.
Structuring a real Python project
A conventional layout — src/, tests/, pyproject.toml — makes a project immediately recognizable and installable.
A common, well-understood layout puts the installable package under src/package_name/, tests in a parallel tests/ directory (mirroring the package's internal structure), and a pyproject.toml at the project root declaring metadata, dependencies and tool configuration in one place. The src/ layout (versus putting the package directly at the project root) specifically prevents accidentally importing the local, possibly-stale source instead of the properly installed package during testing, catching packaging mistakes that a flat layout can hide. PyPA treats src/ layout and flat layout as both valid, supported approaches with different trade-offs rather than one being required by tooling — flat layout stays simpler for some projects, while src/ layout's import-safety advantage is what makes it the common recommendation for installable packages.
Key points
- The src/package_name/ layout, with a parallel tests/ directory, is a common, often-recommended shape for installable packages — not the only valid one
- src/ layout prevents accidentally testing against stale local source instead of the installed package
- One pyproject.toml at the root declares metadata, dependencies and tool configuration together
Code
myproject/
pyproject.toml
src/
myproject/
__init__.py
core.py
tests/
test_core.py
README.mdA conventional src-layout project structure that most Python tooling recognizes without extra configuration.
Common pitfalls
- Putting the package directly at the project root (flat layout) can let tests accidentally import uninstalled local source
- Scattering configuration across setup.cfg, setup.py, and separate tool config files instead of consolidating in pyproject.toml adds unnecessary complexity
Practice exercise
Reorganize a flat script-based project of yours into a src-layout package with a pyproject.toml and a tests/ directory, then confirm pip install -e . and pytest both still work.