W09: Rules as Small Typed, Tested Functions

A good recipe card says: 200 g flour, 2 eggs, mix, bake 20 minutes at 180 °C. It does not say "use whatever is in the fridge" or "bake until it feels right". Give the same card to anyone, with the same ingredients, and they get the same cake. Your app's rules should be written like that: a function takes some data in and gives an answer out, the same every time. Those functions live in app/logic/. Types are the labels on the ingredients, and a checker called pyright reads every label for you.

Core and Shell

The stack splits every app into two parts:

The starter's only rule is in app/logic/notes.py:

MAX_TITLE = 120


@dataclass(frozen=True)
class Problem:
    field: str
    key: str


def check_title(title: str) -> tuple[str, list[Problem]]:
    """The title as it will be saved, and what is wrong with it (nothing when it is fine)."""
    clean = " ".join(title.split())
    if not clean:
        return clean, [Problem("title", "error.title_empty")]
    if len(clean) > MAX_TITLE:
        return clean, [Problem("title", "error.title_long")]
    return clean, []

It tidies the spaces, then checks: empty? too long? It does not know about web pages, the database or Japanese. It returns a message key, and the page translates it (W10). The route in main.py just calls it and acts on the answer.

Why Pure Functions?

When a rule needs today's date, the shell reads the clock and passes the date in as a parameter. The function stays pure, and the test can pass any date it likes.

Tests for Rules

The test for check_title is three lines, in tests/test_logic.py:

def test_a_title_is_trimmed_and_must_say_something() -> None:
    assert check_title("  buy   milk ") == ("buy milk", [])
    assert check_title("   ") == ("", [Problem("title", "error.title_empty")])
    assert check_title("x" * (MAX_TITLE + 1))[1] == [Problem("title", "error.title_long")]

Each assert is one example. Good examples cover the normal case, the empty case and the edge (exactly at the limit, one past it). Run them with uv run pytest. This is where the harness's Red and Green come from (W03).

Types: Labels on Everything

A type says what kind of value something is: str (text), int (whole number), bool (yes or no), list[Problem] (a list of problems). In the stack, every function's parameters and its result have types. That is a rule, not a suggestion.

Python itself does not check types when the code runs. pyright does, before anything runs. The starter turns on its strictest mode, in pyproject.toml:

[tool.pyright]
typeCheckingMode = "strict"

Run it:

uv run pyright

Here is the kind of mistake it catches. Someone writes:

clean, problems = check_title(title)
if problems > 0:
    ...

problems is a list, not a number, and pyright says so straight away (in its own words, something like "Operator '>' not supported"). Without types, this bug waits until a real person submits the form. T30: TypeScript shows the same idea in JavaScript; R08: Code Quality explains why "easy to change" is the level that matters most, and types are a big part of it.

Data Has a Shape

Notice Problem and the Note from W08. They are dataclasses: small records with named, typed fields. The stack avoids passing loose dictionaries between files, because a dictionary can hold anything and pyright cannot help. With a dataclass, a typo like note.titel is caught before the app runs.

frozen=True means the record cannot be changed after it is made. Fewer surprises.

What the Harness Does Today, and Soon

Today: tests count for Red and Green, and you or Pi run uv run pyright by hand. Ask for it in your request: "... and make sure uv run pyright passes."

Pi Workbench will do this step for you soon: pyright after every edit, with its errors sent straight back to Pi; a check that sends back any app/logic/ file that imports the database, files, the network, the clock or randomness; and a catalogue of ready, tested blocks (paginate, group by, date ranges, money formatting…) that Pi composes instead of writing logic from scratch.

Asking Pi for a Rule

Describe the rule with examples. Examples become tests:

"A note title cannot contain only numbers. '2026' is refused with the message 'Use some words.'; '2026 plans' is fine. Put the rule in app/logic/notes.py with tests."

This Week's Exercise

  1. Read app/logic/notes.py and tests/test_logic.py. Work out, on paper, what check_title("a" * 120) returns: exactly at the limit.
  2. Ask Pi for the "only numbers" rule above. Check the rule is in app/logic/, and the test has your examples.
  3. Run uv run pyright. Then, in a copy, write if problems > 0: somewhere and run it again. Read the error.
  4. Read R08 and write down which of its three levels types help with.

Key Takeaways

  • Rules live in app/logic/ as pure functions: data in, data out, no database, files, network, clock or randomness
  • The shell (main.py, db.py) reads the world, calls the core and renders
  • Pure functions are easy to test completely with a few examples: normal, empty, edge
  • Every parameter and result has a type; pyright in strict mode finds type mistakes before anything runs
  • Data crosses files as typed dataclasses, not loose dictionaries