Check relationships between fields
Some rules involve more than one field. A valid start and a valid end do not necessarily form a valid interval. An after model validator sees the parsed model and can enforce that relationship in one place.
Return the instance after checking it. The validator should express a domain invariant rather than repair arbitrary contradictory data. Field errors are still reported by the fields themselves; the model-level rule is reached only after those fields have been parsed successfully. Equality at a boundary remains a separate policy decision.
from pydantic import BaseModel
from pydantic import model_validator
class Span(BaseModel):
start: int
end: int
@model_validator(mode="after")
def ordered(self):
if self.end < self.start:
raise ValueError("reversed span")
return self
print(Span(start=2, end=5).end)Your task
Implement span_length(raw) with Span(start: int, end: int). Validate end >= start using a model validator, and return end-start. A zero-length interval is valid.
The explanation opens here once every check passes.