from pydantic import model_validator, ValidationError class Transaction(BaseModel): sender: str | None amount: float | None transaction_id: str | None transaction_date: date | None @model_validator(mode="after") def check_sane_values(self) -> "Transaction": # negative amounts have shown up exactly twice, both times because # the source message described a refund, not a payment if self.amount is not None and self.amount <= 0: raise ValueError(f"amount must be positive, got {self.amount}") if self.transaction_date is not None and self.transaction_date > date.today(): raise ValueError(f"transaction_date {self.transaction_date} is in the future") return self