CLI journal project (5/6): typing and mypy

Protocol, TypedDict, and Literal for log levels, then tighten mypy from a loose config toward strict checks in CI. Twelve exercises for the journal CLI.

Illustration : formes géométriques s'emboîtant dans leurs encoches, inspectées à la loupe, image de la vérification de types

AI-generated illustration

Some links on this page are affiliate links. The button opens Amazon so you can check today’s price.

Define a TypedDict for the final JSON report: {"total": int, "by_level": dict[str, int], ...}. Use Literal["INFO", "ERROR", "WARN"] for the level on LogLine. A Protocol named SupportsReadLines can describe testable sources without depending on Path alone.

Run mypy on the src/ folder: start with disallow_untyped_defs = False, then tighten. Put mypy in CI (GitHub Actions or the equivalent) so type regressions fail the build.

Previous chapter: asyncio and batch reads.

Exercises (12)

Exercise 1 — Annotate def merge_reports(a: Counter, b: Counter) -> Counter. Easy

Show the solution
from collections import Counter

def merge_reports(a: Counter, b: Counter) -> Counter: c = Counter(a) c.update(b) return c

Exercise 2 — A Report TypedDict with keys total and by_level. Intermediate

Show the solution
from typing import TypedDict

class Report(TypedDict): total: int by_level: dict[str, int]

Exercise 3 — The command mypy src journal_stats. Easy

Show the solution
mypy src

Exercise 4 — # type: ignore — when is it acceptable? Intermediate

Show the solution
A poorly typed library; comment with a ticket or a link.

Exercise 5 — assert isinstance for narrowing after json.loads. Hard

Show the solution
def f(x: object) -> dict[str, object]:
    assert isinstance(x, dict)
    return x

Exercise 6 — from __future__ import annotations — a reminder. Easy

Show the solution
# Annotations stored as strings; forward references stay easy.

Exercise 7 — A Protocol with def readlines(self) -> list[str] — a mock in a test. Intermediate

Show the solution
class Fake:
    def readlines(self):
        return ["2026-01-01 00:00:00 INFO hi\n"]

Exercise 8 — A TypedDict with total=False for optional keys. Hard

Show the solution
class R(TypedDict, total=False):
    errors: int

Exercise 9 — The py.typed marker, PEP 561 — why put it in the wheel? Intermediate

Show the solution
It says the package provides stubs or annotations.

Exercise 10 — reveal_type while debugging with mypy. Easy

Show the solution
reveal_type(x)  # type: ignore[misc]

Exercise 11 — CI: mypy fails on a warning — a strategy. Intermediate

Show the solution
Move toward --strict step by step; do not ignore warnings in bulk.

Exercise 12 — Final for the package name as a constant. Hard

Show the solution
from typing import Final
NAME: Final = "journal-stats"

Next

Package and pyproject

Amazon

Check today’s price on Amazon

Further reading

Was this page helpful?

Have a question about this guide or need advice? Ask us here

Torn between two models or stuck on a build? Drop us a line and we will get back to you by email.