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.

PythonData Integrity

Code

pythonsnippet
20 lines
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 early raise when 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

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.