Skip to content

no-frozen-after-validator-field-write

Do not assign declared fields in after-validators on frozen Pydantic models.

Why

Direct field assignment contradicts the model's frozen contract and can fail only when the validator runs, making construction behavior surprising and brittle.

Fix

Validate without mutation, compute the value before constructing the model, or return an explicitly updated model when replacement is part of the design.

Examples

Before — flagged After-validator assigns a frozen model field
app/models.py
from pydantic import BaseModel, ConfigDict, model_validator
class Counter(BaseModel):
model_config = ConfigDict(frozen=True)
value: int
@model_validator(mode="after")
def normalize(self):
self.value = abs(self.value)
return self
After — preferred Before-validator normalizes the input value
app/models.py
from pydantic import BaseModel, ConfigDict, field_validator
class Counter(BaseModel):
model_config = ConfigDict(frozen=True)
value: int
@field_validator("value", mode="before")
@classmethod
def normalize(cls, value: int) -> int:
return abs(value)