I have multiple pydantic 2.x models and instead of applying validation per each literal field on each model
class MyModel(BaseModel):
name: str = ""
description: Optional[str] = None
sex: Literal["male", "female"]
@field_validator("sex", mode="before")
@classmethod
def strip_sex(cls, v: Any, info: ValidationInfo):
if isinstance(v, str):
return v.strip()
return v
I want to use approach similar to this Annotated Validators
How can I achieve automatic validation on all Literal fields?
def strip_literals(v: Any) -> Any:
if isinstance(v, str):
return v.strip()
return v
# doesn't work
# LiteralType = TypeVar("LiteralType", bound=Literal)
# LiteralStripped = Annotated[Literal, BeforeValidator(strip_literals)]
class MyModel(BaseModel):
name: str = ""
description: Optional[str] = None
sex: LiteralStripped["male", "female"]
I want something like above, but cannot actually define proper validation handlers on literals.
You have to move the declaration of the Literal values into the annotation, like so:
Which raises:
In case you would like to avoid the repetition of the annotation, for different Literal values you can define an alias and rely on
__class_getitem__:However this is already an advanced pattern, but it works exactly as you suggested.
I hope this helps.