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.
Dataset
Section titled “Dataset”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.
Requirements
Section titled “Requirements”- A
CustomerRowTypedDict with the ten columns above and their types.total_chargesisfloat | None. PlanandContractastypealiases ofLiteraltypes. The loader rejects a value outside them withValueError, usingget_argson the alias (no second hand-written list).load_customers(path: Path) -> list[CustomerRow].- A
Rulealias,Callable[[CustomerRow], bool], and a registryRULES: 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). - A
ScorerProtocol withscore(self, customer: CustomerRow) -> float, and aRuleScorerclass that matches it without inheriting from it. - A generic helper
top_k[T](items, k, key)in the PEP 695 syntax. - A
report(customers, scorer, k)function that prints the report below. It accepts anyScorer. mypy --strict churn_score.pyprintsSuccess: no issues found in 1 source file.- At least three
assertchecks: the 10 blanktotal_charges, the overall churn rate and one more of your choice.
The expected report for k=500:
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.69Step plan
Section titled “Step plan”-
Describe one row. Write the two
Literalaliases and theCustomerRowTypedDict. Runmypy --strict churn_score.pynow: an early run catches syntax and import problems while the file is small. -
Parse one row. Write
parse_row(raw: dict[str, str]) -> CustomerRow. Convert each field. A blanktotal_chargesbecomesNone. Return a dict literal: mypy then checks that you filled every key with the right type. -
Validate the literals. Write a small generic function
parse_choice[T](text: str, allowed: tuple[T, ...]) -> Tthat returns the matching allowed value or raisesValueError. Call it withget_args(Plan.__value__). -
Load the file.
load_customersopens the CSV withnewline=""and mapsparse_rowovercsv.DictReader(f). -
Write the rules. Define
type Rule = Callable[[CustomerRow], bool]and theRULESdict. Lambdas are fine: the checker infers their parameter type from theRulehint. -
Write the scorer. A
ScorerProtocol, thenRuleScorerwith__init__(self, rules)andscore(self, customer), which sums the weights of the matching rules. -
Write the helpers and the report.
top_k,churn_rate, amean_knownthat skipsNone, thenreport. Format the churn rates with:.1%. -
Run both tools.
python churn_score.pymust print the expected report.mypy --strict churn_score.pymust succeed. Then break something on purpose (rename a key, return astrfrom a rule) and watch mypy catch it.
A skeleton to start from:
"""Score churn risk in data/customers.csv with typed, pluggable rules."""
import csvfrom collections.abc import Callable, Iterablefrom pathlib import Pathfrom 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 assertsRubric
Section titled “Rubric”| 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 |
Stretch goals
Section titled “Stretch goals”- Write a second scorer,
TenureScorer, whose score is1 / (1 + tenure_months), and pass it toreportunchanged. Compare the churn rate of its top 500. - Replace the hand-written
parse_rowchecks with pydantic:TypeAdapter(CustomerRow).validate_python(...). pydantic converts"72"to72by itself; check what it does with"0"for abool. - Add
@overloadsignatures to aget_field(customer, name)function so thatget_field(c, "tenure_months")has the typeintandget_field(c, "plan")has the typePlan. - Install pyright (
uv pip install pyright) and run it on your file. Compare its messages with mypy’s. - Add a
[tool.mypy]section withstrict = trueto yourpyproject.toml, so that a plainmypy .checks the whole folder strictly.
Reference solution
Section titled “Reference solution”Try the project yourself first. Then compare. Your names can differ; the report and the strict check must not.
Reference solution
"""Score churn risk in data/customers.csv with typed, pluggable rules."""
import csvfrom collections.abc import Callable, Iterablefrom pathlib import Pathfrom 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())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.69mypy --strict churn_score.pySuccess: no issues found in 1 source fileHow it works:
- Records.
CustomerRowturns each CSV row into a typed dict.parse_rowreturns a dict literal, so mypy checks every key and value type against the TypedDict. The conversions happen once, at the boundary. - Literals.
get_args(Plan.__value__)returns('basic', 'standard', 'premium'), so the runtime check uses the same values as the type.parse_choiceis generic, butget_argsreturnstuple[Any, ...], so hereTbecomesAny. The runtime check, not the checker, guarantees the value. That is the honest limit of typing data from a file. - Rules. Each lambda in
RULESis checked againstRule. A rule that readsc["tenure"]or returns a string failsmypy --strict. Adding a rule is one new line. - Protocol.
reportdepends onScorer, not onRuleScorer. Any object with a matchingscoremethod plugs in, including the stretch goal’sTenureScoreror a wrapper around a trained model. - Report. The top 500 customers by score churn at 55.8%, almost three times the 19.3% base rate. The 10 blank
total_chargesare skipped bymean_knowninstead of being counted as 0. - 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.