PythiloLesson 12 of 20 · progress kept in this browser

Validate a parsed field value

An after validator runs once a field has passed its ordinary type validation. Its input can therefore be treated as the annotated type, which makes domain checks simpler. Return the value after checking it; forgetting the return changes the model's field value.

Raise ValueError for a failed domain condition. An accidental TypeError indicates a programming mistake and should not be used as a normal validation result. Keep a validator focused on one field unless the rule genuinely needs several fields together.

from pydantic import BaseModel
from pydantic import field_validator
class Even(BaseModel):
    value: int
    @field_validator("value")
    @classmethod
    def even(cls, value):
        if value % 2:
            raise ValueError("must be even")
        return value
print(Even(value="4").value)
Your task

Implement even_count(raw) through a Count model whose integer value must be even. Permit integer-string conversion and negative even numbers; reject odd values.

The first run loads pydantic into this browser.