Skip to content
Sarj Code Standards

no-pydantic-validator-decorator

Encode Pydantic invariants in field types instead of validator hooks.

Why

A validator hook means the declared types admit values the model rejects; the invariant lives in imperative code that readers, type checkers and schemas cannot see.

Fix

Make illegal states unrepresentable: use Literal, Enum, constrained or Annotated types, Field bounds, nested models or discriminated unions so the field types alone define the valid values, and name any remaining refined type once at module level.

Examples

Before — flagged A validator rejects values the field type accepts
app/models.py
from pydantic import BaseModel, field_validator
class Order(BaseModel):
status: str
@field_validator("status")
@classmethod
def known(cls, status: str) -> str:
if status not in {"open", "closed"}:
raise ValueError(status)
return status
After — preferred The field type admits only valid values
app/models.py
from typing import Literal
from pydantic import BaseModel
class Order(BaseModel):
status: Literal["open", "closed"]