Skip to content

12. Type hints — Mini-project

The retention team wants a short list of subscription customers to call this week. A data scientist will train a real model later (module 36). Today, you build a transparent rule-based score: each warning rule (month-to-month contract, short tenure, few logins, many support tickets, no autopay) adds a weight, and the customers with the highest scores go on the call list.

The code will grow: other people will add rules and other scorers. So the module must be fully typed, and mypy --strict must pass. A new rule with the wrong signature, a misspelled column or an invalid plan name must fail the check, not the Monday report.

Write churn_score.py. It loads the CSV into typed records, scores every customer, prints a report and passes mypy --strict.

data/customers.csv: 5,000 customers, one row each, snapshot 2024-12-31. The columns this project uses:

Column CSV text Your type
customer_id C00001 str
plan basic, standard, premium Literal alias Plan
contract month-to-month, one-year, two-year Literal alias Contract
has_autopay 0 or 1 bool
tenure_months 0 to 72 int
monthly_charges 84.69 float
total_charges 5969.85, blank for 10 new customers float | None
support_tickets 0 to 9 int
logins_last_30d 0 to 60 int
churned 0 or 1 bool

The overall churn rate is 19.26%. csv.DictReader gives every value as text, so each one needs a conversion.

  1. A CustomerRow TypedDict with the ten columns above and their types. total_charges is float | None.
  2. Plan and Contract as type aliases of Literal types. The loader rejects a value outside them with ValueError, using get_args on the alias (no second hand-written list).
  3. load_customers(path: Path) -> list[CustomerRow].
  4. A Rule alias, Callable[[CustomerRow], bool], and a registry RULES: dict[str, tuple[Rule, float]] with these five rules and weights: month-to-month contract (2.0), tenure of 6 months or less (2.0), 3 logins or fewer (1.5), 3 support tickets or more (1.0), no autopay (0.5).
  5. A Scorer Protocol with score(self, customer: CustomerRow) -> float, and a RuleScorer class that matches it without inheriting from it.
  6. A generic helper top_k[T](items, k, key) in the PEP 695 syntax.
  7. A report(customers, scorer, k) function that prints the report below. It accepts any Scorer.
  8. mypy --strict churn_score.py prints Success: no issues found in 1 source file.
  9. At least three assert checks: the 10 blank total_charges, the overall churn rate and one more of your choice.

The expected report for k=500:

Expected output
Customers: 5,000 overall churn: 19.3%
month_to_month w=2.0 2,784 hit, churn 29.6%
new_customer w=2.0 1,110 hit, churn 44.0%
inactive w=1.5 395 hit, churn 42.5%
many_tickets w=1.0 694 hit, churn 38.6%
no_autopay w=0.5 2,355 hit, churn 21.9%
Top 500 by score: churn 55.8%
Mean total charges: 1,385.69
  1. Describe one row. Write the two Literal aliases and the CustomerRow TypedDict. Run mypy --strict churn_score.py now: an early run catches syntax and import problems while the file is small.

  2. Parse one row. Write parse_row(raw: dict[str, str]) -> CustomerRow. Convert each field. A blank total_charges becomes None. Return a dict literal: mypy then checks that you filled every key with the right type.

  3. Validate the literals. Write a small generic function parse_choice[T](text: str, allowed: tuple[T, ...]) -> T that returns the matching allowed value or raises ValueError. Call it with get_args(Plan.__value__).

  4. Load the file. load_customers opens the CSV with newline="" and maps parse_row over csv.DictReader(f).

  5. Write the rules. Define type Rule = Callable[[CustomerRow], bool] and the RULES dict. Lambdas are fine: the checker infers their parameter type from the Rule hint.

  6. Write the scorer. A Scorer Protocol, then RuleScorer with __init__(self, rules) and score(self, customer), which sums the weights of the matching rules.

  7. Write the helpers and the report. top_k, churn_rate, a mean_known that skips None, then report. Format the churn rates with :.1%.

  8. Run both tools. python churn_score.py must print the expected report. mypy --strict churn_score.py must succeed. Then break something on purpose (rename a key, return a str from a rule) and watch mypy catch it.

A skeleton to start from:

churn_score.py (starter)
"""Score churn risk in data/customers.csv with typed, pluggable rules."""
import csv
from collections.abc import Callable, Iterable
from pathlib import Path
from typing import Literal, Protocol, TypedDict, get_args
type Plan = Literal["basic", "standard", "premium"]
# TODO: type Contract
class CustomerRow(TypedDict):
customer_id: str
# TODO: the other nine columns
# TODO: parse_choice, parse_row, load_customers
# TODO: type Rule and RULES
# TODO: class Scorer(Protocol) and class RuleScorer
# TODO: top_k, churn_rate, mean_known, report
if __name__ == "__main__":
customers = load_customers(Path("data/customers.csv"))
# TODO: report(...) and the asserts
Criterion Points Full points when
Runs 2 python churn_score.py prints the expected report exactly
Strict check 3 mypy --strict churn_score.py succeeds with no # type: ignore and no Any in your own hints
Records 2 CustomerRow has all ten keys with precise types, including float | None
Literals 2 Plan and Contract are Literal aliases, and invalid values raise ValueError via get_args
Callables 2 Rule is a Callable alias, and RULES is typed with it
Protocol 2 report accepts a Scorer Protocol; RuleScorer matches it without inheritance
Generics 1 top_k uses the PEP 695 syntax and keeps the item type
Self-checks 1 At least three meaningful assert statements
Readability 1 Docstrings on the main functions; names say what values mean
Total 16 13 or more: you are ready for module 13
  1. Write a second scorer, TenureScorer, whose score is 1 / (1 + tenure_months), and pass it to report unchanged. Compare the churn rate of its top 500.
  2. Replace the hand-written parse_row checks with pydantic: TypeAdapter(CustomerRow).validate_python(...). pydantic converts "72" to 72 by itself; check what it does with "0" for a bool.
  3. Add @overload signatures to a get_field(customer, name) function so that get_field(c, "tenure_months") has the type int and get_field(c, "plan") has the type Plan.
  4. Install pyright (uv pip install pyright) and run it on your file. Compare its messages with mypy’s.
  5. Add a [tool.mypy] section with strict = true to your pyproject.toml, so that a plain mypy . checks the whole folder strictly.

Try the project yourself first. Then compare. Your names can differ; the report and the strict check must not.

Reference solution
churn_score.py
"""Score churn risk in data/customers.csv with typed, pluggable rules."""
import csv
from collections.abc import Callable, Iterable
from pathlib import Path
from typing import Literal, Protocol, TypedDict, get_args
type Plan = Literal["basic", "standard", "premium"]
type Contract = Literal["month-to-month", "one-year", "two-year"]
class CustomerRow(TypedDict):
customer_id: str
plan: Plan
contract: Contract
has_autopay: bool
tenure_months: int
monthly_charges: float
total_charges: float | None # blank for 10 brand-new customers
support_tickets: int
logins_last_30d: int
churned: bool
def parse_choice[T](text: str, allowed: tuple[T, ...]) -> T:
"""Return text as one of the allowed literal values, or raise ValueError."""
for value in allowed:
if value == text:
return value
raise ValueError(f"{text!r} is not one of {allowed}")
def parse_row(raw: dict[str, str]) -> CustomerRow:
"""Convert one CSV row of text into a typed record."""
total = raw["total_charges"]
return {
"customer_id": raw["customer_id"],
"plan": parse_choice(raw["plan"], get_args(Plan.__value__)),
"contract": parse_choice(raw["contract"], get_args(Contract.__value__)),
"has_autopay": raw["has_autopay"] == "1",
"tenure_months": int(raw["tenure_months"]),
"monthly_charges": float(raw["monthly_charges"]),
"total_charges": float(total) if total else None,
"support_tickets": int(raw["support_tickets"]),
"logins_last_30d": int(raw["logins_last_30d"]),
"churned": raw["churned"] == "1",
}
def load_customers(path: Path) -> list[CustomerRow]:
with path.open(encoding="utf-8", newline="") as f:
return [parse_row(raw) for raw in csv.DictReader(f)]
type Rule = Callable[[CustomerRow], bool]
RULES: dict[str, tuple[Rule, float]] = {
"month_to_month": (lambda c: c["contract"] == "month-to-month", 2.0),
"new_customer": (lambda c: c["tenure_months"] <= 6, 2.0),
"inactive": (lambda c: c["logins_last_30d"] <= 3, 1.5),
"many_tickets": (lambda c: c["support_tickets"] >= 3, 1.0),
"no_autopay": (lambda c: not c["has_autopay"], 0.5),
}
class Scorer(Protocol):
def score(self, customer: CustomerRow) -> float: ...
class RuleScorer:
"""Add up the weights of the rules that a customer matches."""
def __init__(self, rules: dict[str, tuple[Rule, float]]) -> None:
self.rules = rules
def score(self, customer: CustomerRow) -> float:
return sum(weight for rule, weight in self.rules.values() if rule(customer))
def top_k[T](items: Iterable[T], k: int, key: Callable[[T], float]) -> list[T]:
return sorted(items, key=key, reverse=True)[:k]
def churn_rate(customers: list[CustomerRow]) -> float:
return sum(c["churned"] for c in customers) / len(customers)
def mean_known(values: Iterable[float | None]) -> float | None:
known = [v for v in values if v is not None]
return sum(known) / len(known) if known else None
def report(customers: list[CustomerRow], scorer: Scorer, k: int) -> None:
print(f"Customers: {len(customers):,} overall churn: {churn_rate(customers):.1%}")
for name, (rule, weight) in RULES.items():
hits = [c for c in customers if rule(c)]
rate = churn_rate(hits)
print(f" {name:<15} w={weight:<4} {len(hits):>5,} hit, churn {rate:.1%}")
flagged = top_k(customers, k, key=scorer.score)
print(f"Top {k} by score: churn {churn_rate(flagged):.1%}")
mean_total = mean_known(c["total_charges"] for c in customers)
print("Mean total charges:", "n/a" if mean_total is None else f"{mean_total:,.2f}")
if __name__ == "__main__":
customers = load_customers(Path("data/customers.csv"))
report(customers, RuleScorer(RULES), k=500)
blanks = sum(c["total_charges"] is None for c in customers)
assert blanks == 10
assert round(churn_rate(customers), 4) == 0.1926
assert RuleScorer(RULES).score(customers[0]) <= sum(w for _, w in RULES.values())
Output
Customers: 5,000 overall churn: 19.3%
month_to_month w=2.0 2,784 hit, churn 29.6%
new_customer w=2.0 1,110 hit, churn 44.0%
inactive w=1.5 395 hit, churn 42.5%
many_tickets w=1.0 694 hit, churn 38.6%
no_autopay w=0.5 2,355 hit, churn 21.9%
Top 500 by score: churn 55.8%
Mean total charges: 1,385.69
Terminal
mypy --strict churn_score.py
Output
Success: no issues found in 1 source file

How it works:

  1. Records. CustomerRow turns each CSV row into a typed dict. parse_row returns a dict literal, so mypy checks every key and value type against the TypedDict. The conversions happen once, at the boundary.
  2. Literals. get_args(Plan.__value__) returns ('basic', 'standard', 'premium'), so the runtime check uses the same values as the type. parse_choice is generic, but get_args returns tuple[Any, ...], so here T becomes Any. The runtime check, not the checker, guarantees the value. That is the honest limit of typing data from a file.
  3. Rules. Each lambda in RULES is checked against Rule. A rule that reads c["tenure"] or returns a string fails mypy --strict. Adding a rule is one new line.
  4. Protocol. report depends on Scorer, not on RuleScorer. Any object with a matching score method plugs in, including the stretch goal’s TenureScorer or a wrapper around a trained model.
  5. Report. The top 500 customers by score churn at 55.8%, almost three times the 19.3% base rate. The 10 blank total_charges are skipped by mean_known instead of being counted as 0.
  6. Self-checks. The asserts run after the report: 10 blanks, the churn rate of 19.26% from the data dictionary, and a score that cannot exceed the sum of all weights.

Alternative: model the records with a frozen dataclass (module 21) instead of a TypedDict: attribute access (c.tenure_months), and a from_csv_row class method for the parsing. A TypedDict fits better when the data must stay a plain dict, for example to serialize it back to JSON.