An operation may produce a value or an expected failure. Separate classes give each outcome a distinct shape, so a caller can inspect which one it received before reading its fields.
from dataclasses import dataclass
@dataclass(frozen=True)
class Accepted:
minutes: int
@dataclass(frozen=True)
class Rejected:
reason: str
def parse_duration(text: str) -> Accepted | Rejected:
try:
minutes = int(text)
except ValueError:
return Rejected("not an integer")
if minutes < 0:
return Rejected("negative duration")
return Accepted(minutes)
def explain(result: Accepted | Rejected) -> str:
if isinstance(result, Accepted):
return f"Duration: {result.minutes} minutes"
if isinstance(result, Rejected):
return f"Rejected: {result.reason}"
raise TypeError("unexpected outcome")
print(explain(parse_duration("12")))
print(explain(parse_duration("noon")))
print(explain(parse_duration("-1")))
Duration: 12 minutes
Rejected: not an integer
Rejected: negative duration
@dataclass supplies an initializer; frozen=True prevents ordinary field reassignment but does not deeply freeze mutable field contents. The union describes either class without requiring a shared parent. isinstance chooses the matching branch, while the final error handles unexpected runtime values. The text: str annotation is not input validation; this function assumes callers supply a string.
Returning failure as data is a design choice, not a rule that all exceptions must disappear. Here the conversion’s expected ValueError becomes a Rejected value; unexpected failures can still propagate. A result model makes success and failure explicit, but Python does not automatically ensure every caller handles both.