Search code examples
pythonpydantic

How to validate a pydantic object after editing it


Is there any obvious way to validate a pydantic model after changing some attribute?

Say I create a simple Model and object:

from pydantic import BaseModel

class A(BaseModel):
    b: int = 0
        
a=A()

Then edit it, so that it is actually invalid:

a.b = "foobar"

Can I force a re-validation and expect a ValidationError to be raised?

I tried

A.validate(a)                      # no error
a.copy(update=dict(b='foobar'))    # no error

What did work was

A(**dict(a._iter()))

ValidationError: 1 validation error for A
b
  value is not a valid integer (type=type_error.integer)

But that is not really straightforward and I need to use the supposedly private method _iter.

Is there a clean alternative?


Solution

  • pydantic can do this for you, you just need validate_assignment:

    from pydantic import BaseModel
    
    class A(BaseModel):
        b: int = 0
    
        class Config:
            validate_assignment = True