Dataclass Post Init Validation

Enforce cross-field invariants in __post_init__ with frozen dataclasses so invalid domain objects raise at construction, not deep in business logic.

PythonData Integrity

Code

pythonsnippet
41 lines
from dataclasses import dataclass, field


@dataclass(frozen=True)
class PriceBand:
    low: int
    high: int
    label: str = field(default='')

    def __post_init__(self) -> None:
        # 冻结实例的跨字段不变量在构造时一次锁定
        if self.low < 0 or self.high < 0:
            raise ValueError(f'prices must be non-negative: {self.low}..{self.high}')
        if self.low > self.high:
            raise ValueError(f'inverted band: {self.low} > {self.high}')
        if not self.label:
            object.__setattr__(self, 'label', f'{self.low}-{self.high}')


@dataclass(frozen=True)
class Inventory:
    items: tuple[PriceBand, ...] = ()

    def __post_init__(self) -> None:
        if not isinstance(self.items, tuple):
            # 可变默认值是坑:强制调用方传 tuple
            raise TypeError('items must be a tuple of PriceBand')


if __name__ == '__main__':
    band = PriceBand(100, 500)
    print(band.label)

    for bad in (PriceBand(-1, 5), PriceBand(9, 3)):
        try:
            bad
        except ValueError as exc:
            print('rejected:', exc)

    inventory = Inventory(items=(band,))
    print(inventory)

What the code does

The code’s whole job belongs to the classes PriceBand and Inventory and the function __post_init__.

Iteration happens inside for bad in (PriceBand(-1, 5), PriceBand(9, 3)) — everything outside it runs once. Invalid states are rejected up front: it throws ValueError and TypeError instead of continuing with bad data.

What to watch for

  • The guard self.low < 0 or self.high < 0 short-circuits the flow with an early raise when its condition holds.

Applying it

Entry signature: def __post_init__(self) -> None

The demo output is labeled (rejected:), so every printed line maps back to its originating operation.

Statements that matter

def __post_init__(self) -> None:
    if not isinstance(self.items, tuple):
        # 可变默认值是坑:强制调用方传 tuple
        raise TypeError('items must be a tuple of PriceBand')
except ValueError as exc:
    print('rejected:', exc)

Interactive Tools for This Topic

FAQ

What happens if the preconditions do not hold?
The code refuses to continue: `ValueError` and `TypeError` is thrown while the state is still recoverable.
What does Dataclass Post Init Validation print when run?
Running the file directly is enough — expect labeled output lines such as `rejected:`.