Type Hints and Testing: assert and pytest Basics
GradeBook class like the ones you have been writing, and it works on the numbers you tried. Then you feed it a CSV file, every score arrives as text, and the crash happens in a different method from the one that made the mistake. You read a library function and cannot tell what it wants. You change one line and cannot tell whether something else broke.assert, then pytest for the basics: test functions, pytest.raises, a first parametrized test, and running it all from the terminal.It follows the lesson on classes because the examples are classes. Fixtures, mocking and coverage wait for the lesson on pytest in depth.
After this lesson, you will be able to:
- Annotate parameters, return values and attributes with modern hints such as list[int], dict[str, float] and str | None
- Explain what Python does and does not do with a type hint at run time
- Run mypy on a file and fix the mismatch it reports
- Write pytest test functions that use assert, pytest.raises and a first parametrize
- Run pytest from the terminal and read a failure report
Before you start
#A mistake that shows up far from its cause
Here is a small grade book with no hints. A loop reads two lines of "name,score" text and adds them.
class GradeBook:
def __init__(self):
self.grades = {}
def add(self, student, score):
self.grades.setdefault(student, []).append(score)
def average(self, student):
scores = self.grades[student]
return sum(scores) / len(scores)
book = GradeBook()
for line in ["asha,91", "asha,84"]:
name, score = line.split(",")
book.add(name, score)
try:
print(book.average("asha"))
except TypeError as err:
print("TypeError:", err)TypeError: unsupported operand type(s) for +: 'int' and 'str'
score is the text "91", not the number 91. add stored it without complaint, and the error only appeared later inside average, in a line that looks fine. The message points at sum, not at the call that was wrong.score should be a number. If it did, a tool could have flagged the book.add(name, score) line without running anything. That is what the next section adds.#What a type hint is, and what Python does with it
-> and a type after the parentheses for the return value.def add(a: int, b: int) -> int:
return a + b
print(add(2, 3))
print(add("hello", "world"))
print(add.__annotations__)5
helloworld
{'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}
The second call breaks the hints and nothing happens. Python stores the annotations on the function (that is the dictionary in the last line) and never looks at them again. The hints do not convert values, check them, or speed anything up.
So what are they for? Three things. Your editor uses them for completion and warnings. A separate program, a type checker, reads them and reports mismatches. And they are documentation that sits in the signature, where it cannot drift away from the code the way a comment can.
This function has hints for a float, and you run it with plain python (no checker). What is printed?
#The hint syntax you need
| for "or". That is all you need for most code, with no imports. Older code imports List, Dict, Optional and Union from typing. You will see those in older code, and they still work, but write the short forms in new code.Dataset class, using the forms you will meet most often.class Dataset:
"""Feature rows and their integer class labels, kept in step."""
def __init__(self, features: list[list[float]], labels: list[int]) -> None:
if len(features) != len(labels):
raise ValueError(f"{len(features)} rows but {len(labels)} labels")
self.features = features
self.labels = labels
@property
def n_rows(self) -> int:
return len(self.labels)
def split(self, test_fraction: float) -> tuple["Dataset", "Dataset"]:
"""Return (train, test); the last test_fraction of the rows is test."""
cut = int(self.n_rows * (1 - test_fraction))
train = Dataset(self.features[:cut], self.labels[:cut])
test = Dataset(self.features[cut:], self.labels[cut:])
return train, test
def class_counts(self) -> dict[int, int]:
counts: dict[int, int] = {}
for label in self.labels:
counts[label] = counts.get(label, 0) + 1
return counts
data = Dataset([[5.1, 3.5], [4.9, 3.0], [6.2, 3.4], [5.9, 3.0], [6.7, 3.1]], [0, 0, 1, 1, 1])
train, test = data.split(0.4)
print(train.n_rows, test.n_rows, data.class_counts())
try:
Dataset([[1.0], [2.0]], [0])
except ValueError as err:
print("ValueError:", err)3 2 {0: 2, 1: 3}
ValueError: 2 rows but 1 labels
list[list[float]] is a list of rows, each row a list of floats. dict[int, int] maps a class label to a count. n_rows is a property (you met @property in the lesson on classes), so you read it as train.n_rows with no parentheses. -> None says the method returns nothing. tuple["Dataset", "Dataset"] is a pair of two datasets."Dataset" matter. Inside the class body the name Dataset does not exist yet when the method is defined, so writing it bare raises a NameError on Python 3.13 and earlier. A quoted name is a forward reference: a string the checker reads later. (Python 3.14 evaluates annotations lazily and no longer needs the quotes.)#Values that may be missing
None is a different type from one that cannot, and hints let you say so. str | None means "a string, or None".class GradeBook:
def __init__(self) -> None:
self.grades: dict[str, list[float]] = {}
def add(self, student: str, score: float) -> None:
self.grades.setdefault(student, []).append(score)
def average(self, student: str) -> float | None:
scores = self.grades.get(student)
if not scores:
return None
return sum(scores) / len(scores)average now admits that it returns nothing for an unknown student. A caller who forgets that case gets a warning from the checker, as the next section shows. The hint on self.grades is worth writing too, because {} alone does not say what will go inside.#Functions as arguments
Callable, imported from collections.abc. You write the argument types in a list, then the return type: Callable[[list[int], list[int]], float] is a function taking two lists of ints and returning a float, like an accuracy metric.from collections.abc import Callable
def accuracy(y_true: list[int], y_pred: list[int]) -> float:
hits = sum(t == p for t, p in zip(y_true, y_pred))
return hits / len(y_true)
def evaluate(metric: Callable[[list[int], list[int]], float],
y_true: list[int], y_pred: list[int]) -> str:
return f"{metric.__name__}: {metric(y_true, y_pred):.2f}"
print(evaluate(accuracy, [0, 1, 1, 0], [0, 1, 0, 0]))accuracy: 0.75
#Checking hints with mypy
pip install mypy and run mypy file.py. pyright is another checker that many editors run for you as you type.Take the grade book from the start and add the hints, plus the loop that made the mistake and one more line that uses the result:
# grades_typed.py (mypy is a separate program, so run this in your terminal)
class GradeBook:
def __init__(self) -> None:
self.grades: dict[str, list[float]] = {}
def add(self, student: str, score: float) -> None:
self.grades.setdefault(student, []).append(score)
def average(self, student: str) -> float | None:
scores = self.grades.get(student)
if not scores:
return None
return sum(scores) / len(scores)
book = GradeBook()
for line in ["asha,91", "asha,84"]:
name, score = line.split(",")
book.add(name, score)
avg = book.average("asha")
print(avg + 1)
$ mypy grades_typed.py
grades_typed.py:19: error: Argument 2 to "add" of "GradeBook" has incompatible type "str"; expected "float" [arg-type]
grades_typed.py:22: error: Unsupported operand types for + ("None" and "int") [operator]
grades_typed.py:22: note: Left operand is of type "float | None"
Found 2 errors in 1 file (checked 1 source file)
None case: average may return None, and None + 1 fails.if, the checker knows the type has narrowed:def describe(x: int | None) -> str:
if x is None:
return "missing"
return str(x + 1) # here mypy knows x is an int, not None
print(describe(None), describe(4))missing 5
items: list[str] = [] passes mypy cleanly and still misbehaves. A hint says what you intend. Whether the intent is met is what tests are for, and that is the second half of this lesson.#Reading hints in library code
Once you can write hints you can read them. When you open an unfamiliar function, the signature tells you most of what you would otherwise search the docs for.
# A signature in the style you will meet in libraries (invented for illustration)
def train_test_split(
rows: Sequence[list[float]],
labels: Sequence[int],
*,
test_size: float = 0.25,
seed: int | None = None,
) -> tuple[list[list[float]], list[list[float]], list[int], list[int]]:
...* means the options after it must be passed by name. seed may be an int or None, and None is its default, so the split is random unless you ask otherwise. It returns four things in a fixed order. You learned all of that without running it.Sequence (from collections.abc) means "any list-like container", and Any means "no promise about this". Your editor's hover text shows a signature, and some libraries ship without hints, so the docs remain the source there.#Testing with assert
Three different things can look at your code, and each finds a different kind of mistake.
| Who | When | What it can find |
|---|---|---|
| The Python interpreter | While the program runs | A crash, such as adding a number to text |
| A type checker (mypy) | Before running, from the hints | A call or return that disagrees with the hints |
| Tests (pytest) | When you run them | A wrong answer that has the right type |
assert condition, message does nothing when the condition is true and raises AssertionError when it is false.def average(values: list[float]) -> float:
return sum(values) / len(values)
def test_average_of_three():
assert average([1, 2, 3]) == 2
def test_average_of_one():
assert average([42]) == 42
def test_average_with_negatives():
assert average([-1, 1]) == 0
# a tiny hand-made test runner: call every function whose name starts with test_
for name, func in list(globals().items()):
if name.startswith("test_") and callable(func):
func()
print("passed:", name)passed: test_average_of_three
passed: test_average_of_one
passed: test_average_with_negatives
test_, call each, and report which raised. A runner also keeps going after a failure so you see every broken test at once, which this loop does not. The standard library has one called unittest, built around classes that inherit from TestCase. It works, but most projects use pytest, because a pytest test is a plain function with a plain assert.assert before you move on. Python can be started with python -O, which strips every assert out of the program. Tests are safe from that, since test runners do not use it. Checks on data that came from outside, such as a user's input or an API response, must be an explicit if with raise, which nothing can remove.#Your first pytest tests
pip install pytest. A pytest project can be two files in one folder: the code, and a file whose name starts with test_.# gradebook.py
class GradeBook:
"""Scores per student, each between 0 and 100."""
def __init__(self) -> None:
self.grades: dict[str, list[float]] = {}
def add(self, student: str, score: float) -> None:
if not 0 <= score <= 100:
raise ValueError(f"score must be between 0 and 100, got {score}")
self.grades.setdefault(student, []).append(score)
def average(self, student: str) -> float | None:
scores = self.grades.get(student)
if not scores:
return None
return sum(scores) // len(scores)//, which divides and drops the fraction. That is a bug, and here are the tests that find it.# test_gradebook.py
from gradebook import GradeBook
def test_average_of_two_scores():
book = GradeBook()
book.add("asha", 91)
book.add("asha", 84)
assert book.average("asha") == 87.5
def test_unknown_student_has_no_average():
assert GradeBook().average("nobody") is Nonepytest in that folder. pytest finds test_gradebook.py, imports it, and runs each test_ function.$ pytest -q
F. [100%]
=================================== FAILURES ===================================
__________________________ test_average_of_two_scores __________________________
def test_average_of_two_scores():
book = GradeBook()
book.add("asha", 91)
book.add("asha", 84)
> assert book.average("asha") == 87.5
E AssertionError: assert 87 == 87.5
E + where 87 = average('asha')
E + where average = <gradebook.GradeBook object at 0x10ad2a510>.average
test_gradebook.py:8: AssertionError
=========================== short test summary info ============================
FAILED test_gradebook.py::test_average_of_two_scores - AssertionError: assert...
1 failed, 1 passed in 0.01s
> marker, and gives the value on each side: 87 against 87.5. Plain Python would only say AssertionError. pytest rewrites your assert statements as it imports the test file, so it can record the pieces of the expression and print them. That is why you write a bare assert a == b in pytest and not a method like assertEqual.// to / in gradebook.py, run again, and both tests pass. The hint -> float | None never warned you, because 87 is a perfectly good number as far as the checker is concerned. A test found what the types could not.#Comparing floats
0.1 + 0.2 is 0.30000000000000004, so assert 0.1 + 0.2 == 0.3 fails. For numbers that came out of arithmetic, compare with pytest.approx:import pytest
print(0.1 + 0.2 == 0.3)
print(0.1 + 0.2 == pytest.approx(0.3))False
True
assert result == pytest.approx(0.3). The averages in this lesson are exact, so you can compare them directly.#Expecting errors with pytest.raises
GradeBook.add should refuse a score outside 0 to 100. A test for that has to expect an error, and pytest.raises is how you say so: the test passes if the code inside the with block raises that exception, and fails if it does not.# test_gradebook.py (add to the file)
import pytest
def test_rejects_score_above_100():
book = GradeBook()
with pytest.raises(ValueError, match="between 0 and 100"):
book.add("asha", 105)match is optional. It checks the error message against a pattern, so the test also fails if a different ValueError is raised for a different reason. Leave it out if the message is not part of what you promise.add were changed to accept 105, pytest would report Failed: DID NOT RAISE <class 'ValueError'>. Without pytest.raises, you would have to write a try and except plus an assert False, which is more code and easier to get wrong.#One test, many cases: parametrize
pytest.mark.parametrize runs one test function once per row of data.# test_gradebook.py (add to the file)
@pytest.mark.parametrize("bad_score", [-1, 100.5, 105])
def test_rejects_scores_outside_range(bad_score):
with pytest.raises(ValueError):
GradeBook().add("asha", bad_score)
@pytest.mark.parametrize(
"scores, expected",
[
([90], 90.0),
([90, 80], 85.0),
([100, 0, 50], 50.0),
],
)
def test_average_cases(scores, expected):
book = GradeBook()
for score in scores:
book.add("asha", score)
assert book.average("asha") == expected@ is a decorator, which you met earlier in the track. Read it as "run this test once for each of these values". The first argument names the test's parameters, as a string. The second is a list with one entry per case, and for several parameters each entry is a tuple or list in the same order.-v and every case is its own test, with the values in its name:$ pytest -v
test_gradebook.py::test_average_of_two_scores PASSED [ 11%]
test_gradebook.py::test_unknown_student_has_no_average PASSED [ 22%]
test_gradebook.py::test_rejects_score_above_100 PASSED [ 33%]
test_gradebook.py::test_rejects_scores_outside_range[-1] PASSED [ 44%]
test_gradebook.py::test_rejects_scores_outside_range[100.5] PASSED [ 55%]
test_gradebook.py::test_rejects_scores_outside_range[105] PASSED [ 66%]
test_gradebook.py::test_average_cases[scores0-90.0] PASSED [ 77%]
test_gradebook.py::test_average_cases[scores1-85.0] PASSED [ 88%]
test_gradebook.py::test_average_cases[scores2-50.0] PASSED [100%]
============================== 9 passed in 0.01s ===============================
If one case is wrong, only that case fails and the others still run. That is the main gain over a single test with a loop inside it, where the first failure hides the rest. Parametrize has more features (readable ids, stacking, combining with fixtures), and the lesson on pytest in depth covers them.
One row of the table is wrong: the average of [100, 0] is 50.0, not 60.0. What does pytest report for this test?
#Running pytest from the terminal
pytest already. These are the forms you will use day to day.-v for one line per test and -q for a shorter report. pytest test_gradebook.py runs one file, pytest test_gradebook.py::test_average_cases runs one function, pytest -k "raises" runs the tests whose name contains that text, and pytest -x stops at the first failure.test_*.py or *_test.py, and in them runs the functions named test_*. A function called check_average is never run, and it does not warn you. When nothing is collected, the report says no tests ran and the exit code is 5, which a CI job treats as a failure. Check that the number of passed tests is what you expect.mypy and pytest and reads those codes. The two tools answer different questions, so run both. Two optional habits for later: follow PEP 8 naming (snake_case functions, PascalCase classes), and try a linter such as ruff.#Common mistakes
Using assert to validate input
def set_learning_rate(rate):
assert rate > 0, "rate must be positive" # removed by python -O
return ratepython -O, the assert vanishes and set_learning_rate(-1) returns -1. Use an explicit check for anything that comes from outside:def set_learning_rate(rate):
if rate <= 0:
raise ValueError("rate must be positive")
return rate
print(set_learning_rate(0.01))0.01
A test that never runs
check_average, or one in a file called grades.py, is not collected. With nothing collected the report says no tests ran. Name the file test_*.py and the function test_*, and look at the count of passed tests, not only at whether anything failed.Writing the class name bare inside the class
class Dataset:
def split(self) -> tuple[Dataset, Dataset]: # NameError on Python 3.13 and earlier
...tuple["Dataset", "Dataset"], as in the example above.Comparing floats with ==
assert 0.1 + 0.2 == 0.3 fails, as you saw. Write assert 0.1 + 0.2 == pytest.approx(0.3).#Try it
Dataset.split has the arithmetic backwards, so the train and test sizes swap. The tests assert the right sizes and print a message when they pass.The test asks for 3 training rows and 2 test rows from a 5-row dataset when test_fraction is 0.4, but split returns them the wrong way round. Fix the line that computes cut.
all tests passed
GradeBook with a new method best_student and two finished tests. Add the two the TODOs ask for. The page loads pytest, so pytest.raises works here. In your own folder these tests would live in test_gradebook.py and pytest would find them itself; here a loop at the bottom plays the runner.Tests: Write the two missing tests, then run. Every test should print a passed line.
Then do the real thing in your terminal, where both tools exist.
- Run
pip install pytest mypy, then creategradebook.pyandtest_gradebook.pyfrom the "Your first pytest tests" section, with the//bug inaverage. - Run
pytest -q. Expect1 failed, 1 passed, withassert 87 == 87.5in the report. - Change
//to/ingradebook.pyand runpytest -qagain. Expect2 passed. - Save the typed grade book from the mypy section as
grades_typed.pyand runmypy grades_typed.py. Expect the two errors shown there, then fix the loop withfloat(score)and the last line with anif avg is not None:check, and run mypy again for a clean result.
Interactive Lab
See how Python type hints annotate functions and catch errors before runtime
#Recap
add("hello", "world") runs happily even when the hints say int. A checker such as mypy reads the hints without running your code and reports mismatches, including a str | None result used as if it were never None.list[int], dict[str, float], X | None, tuple[int, str] and Callable[[int], str]. Inside its own class body, quote the class name on Python 3.13 and earlier.test_* in a file named test_*.py, with plain assert lines, and pytest shows both sides of a failing comparison. Use pytest.raises to expect an error, pytest.approx for floats, and parametrize for one test over many inputs. Check outside input with if and raise, never assert.Going further: fixtures, mocking and coverage are in the lesson on pytest in depth, and Pydantic, which enforces types at run time, comes later. Next, inheritance builds on the classes you hinted here.
#Check yourself
This function is hinted -> float, but one branch returns None. def mean(xs: list[float]) -> float: if not xs: return None return sum(xs) / len(xs) print(mean([])) What happens?