I have this pydantic model with a field, and this field could be either an int or a non numeric value like a str or list.
from pydantic import BaseModel, Field
class Foo(BaseModel):
bar: str | list | int = Field('some string', ge=2)
I want it to be that the constraint ge=2
is applied only if the value given to bar
happens to be an int.
foo_instance = Foo(bar='asdf') # constraint should not be applied
foo_instance = Foo(bar=4) # constraint should be applied
Trying the above throws an error:
TypeError: Unable to apply constraint 'ge' to supplied value asdf
How do I ensure pydantic only tries to apply this constraint if the value is numerical (or if the operation can be performed on this value)?
You can apply the validator to just the int value like so:
from pydantic import BaseModel, Field
from typing import Annotated
class Foo(BaseModel):
bar: str | list | Annotated[int, Field(ge=2)]
foo_instance = Foo(bar="asdf")
foo_instance = Foo(bar=4)