Search code examples
pythonvalidationpydantic

Using pydantic to catch an invalid attribute setting


The script below runs without error. I would like to catch the invalid attribute setting on the last line, where the value is not set to a positive integer.

from pydantic.dataclasses import dataclass
from pydantic import PositiveInt


@dataclass
class MyDataClass:
    value: PositiveInt


my_class = MyDataClass(value=10)
my_class.value = -1

Solution

  • If you're not opposed to using pydantic BaseModels you could just tell it to validate assignments as well.

    from pydantic import BaseModel, PositiveInt
    
    class MyDataClass(BaseModel):
        value: PositiveInt
    
        class Config:
            validate_assignment = True
    
    
    my_class = MyDataClass(value=10)
    
    # raises ValidationError
    my_class.value = -1