Dataclass With Post-Init Validation
Validate invariants in a dataclass post-init hook so invalid instances cannot be constructed, keeping bad data out of the rest of the system.
Code
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Money:
amount: int
currency: str = "USD"
def __post_init__(self) -> None:
if not isinstance(self.amount, int):
raise TypeError("amount must be an int number of minor units")
if self.amount < 0:
raise ValueError("amount must be non-negative")
if self.currency not in {"USD", "EUR", "GBP"}:
raise ValueError(f"unsupported currency: {self.currency}")
def add(self, other: "Money") -> "Money":
if other.currency != self.currency:
raise ValueError("cannot add different currencies")
return Money(self.amount + other.amount, self.currency)How it works
Dataclass With Post-Init Validation is built around the class Money and the functions __post_init__ and add.
The failure path is explicit — TypeError and ValueError is raised when the guard condition holds.
What to watch for
- The guard
not isinstance(self.amount, int)short-circuits the flow with an earlyraisewhen its condition holds.
Applying it
Entry signature: def add(self, other: "Money") -> "Money"
add is the public entry point; everything else in the file exists to support it.
Statements that matter
def add(self, other: "Money") -> "Money":
if other.currency != self.currency:
raise ValueError("cannot add different currencies")
return Money(self.amount + other.amount, self.currency)
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Does the code validate its input?
- `TypeError` and `ValueError` is raised at the guard (`not isinstance(self.amount, int)`), so invalid state never reaches the main logic.
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. The file defines `__post_init__`, `add` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.