I have a List
in a pydantic model. I'd like my custom validator to run when the list changes (not only on assignment).
from typing import List
from pydantic import BaseModel, validator
class A(BaseModel):
b: List[int] = []
class Config:
validate_assignment = True
@validator("b")
def positive(cls, v):
assert all(i > 0 for i in v), f"No negative numbers: {v}"
return v
a = A()
a.b = [1, 2, -3] # error
a.b = [1, 2] # no error
a.b.append(-3) # no error
I'd like that last append
to raise an error.
I'll get an error if i try to recreate the object (as expected)
A(**a.dict())
Even appending a wrong type is allowed. Why doesn't this break the model?
a.b.append("asdf") # no error
This is similar/an extension to: How to validate a pydantic object after editing it