Search code examples
pythonpydantic

mypy with pydantic field_validator


With pydantic, is there a way for mypy to be hinted so it doesn't raise an error in this scenario, where there's a field_validator modifying the type?

class MyModel(BaseModel):
    x: int

    @field_validator("x", mode="before")
    @classmethod
    def to_int(cls, v: str) -> int:
        return len(v)


MyModel(x='test')

Solution

  • If you're always inserting a string there, it might be better to use a computed_field. Something along this, maybe?

    class MyModel(BaseModel):
        input: str
    
        @computed_field
        def x(self) -> int:
            return len(self.input)
    

    I think it's very counterintuitive if you see the model with the int declaration while it would raise type errors if you put an integer inside a JSON at that place.