I'm using a field wrap validator in Pydantic with the Annotated pattern, and I want to access the expected/annotated type of a field from within the validator function. Here's an example of what I want:
from typing import Annotated, Any
from pydantic import (
BaseModel, ValidationError, ValidationInfo,
ValidatorFunctionWrapHandler, WrapValidator
)
def wrapper(value: Any,
handler: ValidatorFunctionWrapHandler,
info: ValidationInfo) -> Any:
try:
return handler(value)
except ValidationError as e:
# Custom error handling where I want to know the expected type.
# I'm looking for something like this:
if info.annotation == str:
# Do something
elif info.annotation == int | bool:
# Do something else
else:
raise
class MyModel(BaseModel):
foo: Annotated[str, WrapValidator(wrapper)]
class AnotherModel(BaseModel):
bar: Annotated[int | bool, WrapValidator(wrapper)]
I would have expected ValidationInfo to include the expected data type of value, but it doesn't seem to.
Another option is to go through the model fields. Something like this:
MyModel.model_fields[info.field_name].annotation.
However, this wrapper is applied to multiple models, so I can't just reference MyModel explicitly like that. And again ValidationInfo doesn't seem to include any reference back to the model.
I noticed that info.config = {"title": "MyModel"}. Is there a way to get the MyModel class from the "MyModel" string, and is this a reliable means of finding the model?
This is not a duplicate of this question, which concerns the decorator pattern for validators, not the annotated pattern, and also uses old syntax from v1.