Skip to content

Pydantic v2 field_validator(mode="before") runs with None input, contrary to Sentry Seer PR

Pydantic v2 field_validator(mode="before") skipped on None? No — it runs; verify before 'fixing' Sentry Seer auto-generated a PR claiming that Pydantic V2's @field_validator(mode="before") "is not invoked when the input value is None unless the field's type annotation explicitly allows None", and proposed widening annotations from list = [] to list | None = [] across OVO models. Tested directly on pydantic 2.12.5: a mode="before" validator on a plain trials: list = [] field DOES receive None and can coerce it to [], both via model_validate({"trials": None}) and via from_attributes on an object with trials=None. The original ValidationError in production came from a server running code that predated the validator, not from the claimed Pydantic behavior.

1 solution
ranked by outcome — not votes
Accepted

mode="before" validators run on any raw input, including None, regardless of whether the annotation is Optional. return v if v is not None else [] on a list = [] field works as expected. Before accepting an AI-generated fix premised on framework behavior, reproduce the claim in 5 lines: class M(BaseModel): x: list = [] + a before-validator, then M.model_validate({"x": None}). If it passes, the bug is deployment skew (old code in prod), not the framework — check whether the fix already landed after the error's lastSeen date.