Represent Explicit Service Outcomes
Core idea
A service contract defines accepted inputs, success values and expected failures. A union of named result types lets callers distinguish business rejection from success. Unexpected infrastructure exceptions remain distinct. Type annotations describe the contract for a checker; runtime validation still needs code.
from dataclasses import dataclass@dataclass(frozen=True)class Accepted: remaining: int@dataclass(frozen=True)class Rejected: reason: strdef reserve(stock: int, n: int) -> Accepted | Rejected: if not 0 < n <= stock: return Rejected('unavailable') return Accepted(stock-n)r = reserve(5, 2)print(r.remaining if isinstance(r, Accepted) else r.reason)The caller checks the result type before accessing its field. The service assumes integer quantities.
Expected output:
3Handle a rejected request
from dataclasses import dataclass@dataclass(frozen=True)class Error: reason: strdef lookup(rows: dict[str,int], key: str) -> int | Error: return rows[key] if key in rows else Error('missing')r = lookup({'A':0}, 'B')print(r.reason if isinstance(r, Error) else r)A missing key is distinguishable from a valid zero result.
Expected output:
missingCommon mistake
Do not catch every exception and return the same rejection; this hides infrastructure defects. Specify which failures are expected outcomes and which exceptions propagate.
Practice
Define accepted/rejected results for a capacity service. Test zero, exact capacity and exceeding capacity, then document an unexpected storage error policy.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Typed service contracts
Check your understanding of typed service contracts.
What is printed?
def f(x: int)->int: return xprint(type(f("x")).__name__)What is printed?
from dataclasses import dataclass@dataclassclass Fail: reason:strprint(Fail("full").reason)Why use separate result types?
What remains necessary at external input boundaries?