본문으로 건너뛰기

P9 — Writing Reliable Python: Contracts, Validation, Tests

About 75 min

Before L10.1, work through this bridge if validation and tests are unfamiliar. L9.9 starts using checked records; L10.2 and L10.6 ask you to reason about argument boundaries and legal transitions. P3 covers functions; P8 covers local execution. If you get every question below right, you can move to the next lesson. This non-numbered bridge and its checks/Lab never count toward course progress. Budget 60–90 minutes.

Quick Check

1. A function expects a nonempty list of IDs. What is part of its contract?
2. Does a parameter annotation x: int automatically reject a string at runtime?
3. What does raise ValueError('bad') do?
4. Should an undefined state/event pair be accepted by default?

0 of 4 questions answered.

Goal

Write a small function contract, validate untrusted dictionaries, distinguish raising from catching exceptions, read type hints, reject illegal state transitions, and prove both successful and failing behavior with tests.

1. A function contract has three parts (10 minutes)​

For reserve_seats(request), write down preconditions (what request is accepted), postconditions (what successful result looks like), and failure behavior (which invalid cases raise). A comment that only says "returns a dictionary" is not a contract.

def reserve_seats(request: dict) -> dict:
"""Accept a code and 1–4 seats. Return a normalized reservation."""
if not isinstance(request, dict):
raise TypeError("request must be a dictionary")
code = request.get("code")
seats = request.get("seats")
if not isinstance(code, str) or not code.strip():
raise ValueError("code must be nonempty")
if type(seats) is not int or not 1 <= seats <= 4:
raise ValueError("seats must be an integer from 1 to 4")
return {"code": code.strip(), "seats": seats}

isinstance(True, int) is true in Python. Using type(seats) is int deliberately excludes booleans from a numeric field. The annotation request: dict explains an intended shape, but Python does not validate that annotation on call. Inspect the conditions, not just the signature.

2. Check a dictionary at the boundary (15 minutes)​

JSON objects decode to Python dictionaries. Treat outside fields as untrusted even when a model or a client claims they match a schema. Check that the object is a dict before reading its keys. A minimal schema can specify required names, allowed names, value types, enums, and ranges.

def check_job(payload: object) -> dict:
if not isinstance(payload, dict):
raise TypeError("job must be an object")
allowed = {"job_id", "priority"}
missing = {"job_id"} - payload.keys()
extra = payload.keys() - allowed
if missing:
raise ValueError("missing: job_id")
if extra:
raise ValueError("extra fields")
job_id = payload["job_id"]
priority = payload.get("priority", "normal")
if not isinstance(job_id, str) or not job_id.strip():
raise ValueError("invalid job_id")
if priority not in ("normal", "urgent"):
raise ValueError("invalid priority")
return {"job_id": job_id.strip(), "priority": priority}

A validated object is not automatically authorized. Schema validation proves shape and accepted values; application policy must separately decide whether the requester may perform the operation. Never use unchecked model-generated arguments as commands.

3. Raise at the boundary; catch where you can respond (10 minutes)​

try:
job = check_job({"job_id": "job-7", "priority": "instant"})
except (TypeError, ValueError) as error:
print("Rejected:", error)
else:
print("Accepted:", job)

raise signals a failed contract. except is for a caller that knows how to handle that specific problem. The else branch runs only if no exception happened. Do not use except Exception: pass: it hides programming errors as if inputs were valid. Avoid catching errors just to convert them into "success."

Read these annotations in later Labs: list[str] means a list of strings, dict[str, int] maps strings to integers, str | None allows a string or None, and tuple[bool, str] is a two-item return description. Annotations aid reading and tools; they do not replace checks.

4. A state machine makes illegal shortcuts visible (15 minutes)​

Define each allowed (state, event) → next_state pair explicitly. Below is a document-review workflow, not the order/refund workflow of L10.6.

TRANSITIONS = {
("DRAFT", "submit"): "UNDER_REVIEW",
("UNDER_REVIEW", "request_changes"): "DRAFT",
("UNDER_REVIEW", "approve"): "APPROVED",
("APPROVED", "publish"): "PUBLISHED",
}

def advance(state: str, event: str) -> str:
try:
return TRANSITIONS[(state, event)]
except KeyError as error:
raise ValueError(f"illegal transition: {state} + {event}") from error

Trace DRAFT → submit → UNDER_REVIEW → approve → APPROVED. Predict what happens if publish arrives while the state is DRAFT: it must raise, not silently publish. Real workflows additionally track principal/permission, an action's idempotency key, external side effects, and a retry limit.

Predict

A reviewer tries publish while the document is UNDER_REVIEW. What does advance do?

5. Test failures as deliberately as success (15 minutes)​

A passing example alone cannot show whether invalid input was rejected. Build two files in the same directory, so tests can import exactly the functions they exercise:

  1. Create contract_demo.py. Copy the complete check_job definition from Section 2 and the TRANSITIONS table plus advance definition from Section 4 into it. Keep only those definitions; no server or API is needed.
  2. Create test_contract_demo.py with the following code. The first two lines explicitly import the functions from contract_demo.py.
import unittest
from contract_demo import check_job, advance

class ContractTests(unittest.TestCase):
def test_valid(self):
self.assertEqual(check_job({"job_id": " a "}), {"job_id": "a", "priority": "normal"})

def test_bad_priority(self):
with self.assertRaises(ValueError):
check_job({"job_id": "a", "priority": "instant"})

def test_illegal_transition(self):
with self.assertRaises(ValueError):
advance("DRAFT", "publish")

if __name__ == "__main__":
unittest.main()

From the directory containing both files, run python -m unittest -v test_contract_demo. You should see three passing tests, including the two expected failures. If an import fails, check both filenames and confirm that contract_demo.py contains the definitions from Sections 2 and 4. If pytest is installed, you can make the same rejection assertion in a third file with different syntax:

import pytest
from contract_demo import check_job

def test_bad_priority():
with pytest.raises(ValueError):
check_job({"job_id": "a", "priority": "instant"})

Save this as test_contract_pytest.py (leave the unittest test file intact) and run python -m pytest test_contract_pytest.py. Pytest is optional here (install it with python -m pip install pytest inside your virtual environment if you want to try it); P9's browser Lab uses the standard library. Fixtures are fixed sample inputs and expected outputs; keep them independent of live APIs.

Guided offline browser Lab (15 minutes)​

Implement a different pair of boundaries: validate a small library checkout request, then advance a checkout state through explicitly declared transitions. The starter contains TODOs and deliberately separate tests for missing/extra/type-invalid fields and illegal transitions. This follows the patterns of L10.2/L10.6 without copying their order schema or approval transitions. Three progressive hints and a complete answer are available. No internet, packages or model weights are required.

Loading lab…

Quick Check

1. A JSON field count contains true. Why explicitly check type(count) is int?
2. Which test proves unknown fields are rejected?
3. Which claim is correct after payload shape validation passes?
4. What should code do with an undefined state/event pair?

0 of 4 questions answered.

Key Takeaways

  • A contract specifies inputs, outputs, and failures; type hints are not runtime validation.
  • Validate dict shape, allowed keys, values, and separate authorization before side effects.
  • Use named exceptions and negative tests instead of swallowing failures.
  • Encode legal state/event pairs explicitly and test forbidden shortcuts.
  • P9 is a non-numbered preparation guide; required Level 10 Labs and progress are unchanged.

Next Lesson

Continue to L10.1 — LLMs That Use Tools, then use these techniques in L10.2 and L10.6.