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.
Code
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 < 0short-circuits the flow with an earlyraisewhen 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
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
- 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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.