prefer-explicit-value-model-construction
Prefer declared validation and explicit factories over value-model initialization hooks.
Why
Handwritten post-initialization hooks hide validation and normalization in a separate construction phase. Repeated scalar checks can diverge from field contracts, while implicit mutation and effects make a value model harder to construct and reason about.
Fix
Express scalar constraints in Pydantic fields and keep cross-field validation in an explicit native validator. Use a named typed factory for deliberate construction work or side effects. Preserve strictness, immutability and cross-field invariants when replacing a hook; do not merely delete it.
Examples
from dataclasses import dataclass
@dataclass(frozen=True, slots=True)class AudioObject: generation: int
def __post_init__(self) -> None: if type(self.generation) is not int or self.generation <= 0: raise ValueError("generation must be a positive integer")from typing import Annotatedfrom pydantic import BaseModel, ConfigDict, Field
class AudioObject(BaseModel): model_config = ConfigDict(frozen=True) generation: Annotated[int, Field(strict=True, gt=0)]