I have a project using fastapi and pydantic. I want to define certain subtypes of standard library types, eg:
def check_negative(v: int) -> int:
assert v >= 0, f"{v} is negative"
return v
PositiveInt = Annotated[int, AfterValidator(check_negative)]
class DemoModel(BaseModel):
numbers: list[PositiveInt]
ISSUE:
The following code runs the evaluation only when the list of numbers is passed on instantiation of the DemoModel. Meaning numbers contains false values until it is actually used in a BaseModel. This is unconvenient since i want to evaluate the value, for example, directly in the route of a defined fastapi endpoint and not wait until the value is passed down to the model.
numbers = [PositiveInt(2), PositiveInt(-3)] <--- should throw evaluation error here
print(numbers)
demo = DemoModel(numbers=numbers) <--- throws evaluation error here
QUESTION:
Is there a way to run the validations like AfterValidator directly on the instantiation of the type PositiveInt and not just when it is used for the instantiation of a BaseModel class?
So that in the given example, the validation error would be thrown in the first line numbers = [PositiveInt(2), PositiveInt(-3)] and not at the end at demo = DemoModel(numbers=numbers).
Thanks for your help!