guilatrova / tryceratops

A linter to prevent exception handling antipatterns in Python (limited only for those who like dinosaurs).

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

TRY003 and TRY004 being triggered inside Pydantic's field_validator

TheForgottened opened this issue · comments

TRY003 and TRY004 are currently being flagged inside field_validator method of the Pydantic library.

TRY003 can easily be fixed by creating a new Exception that inherits ValueError, but honestly just seems way too overkill.

TRY002 is not as fixable tho since Pydantic forces the user to raise a ValueError, and raising a TypeError won't integrate well with the library.

E.g.

from pydantic import BaseModel, field_validator
from pydantic_core.core_schema import ValidationInfo

class PersonWithBigName(BaseModel):
    name: str
    surname: str
    age: int

    @field_validator("name")
    def _name_must_be_big(cls, value: str, , info: ValidationInfo) -> str
        if len(value) < 10:
            raise ValueError(f"{info.field_name} must be bigger!")  # TRY003 
        
        return value

    @field_validator("age")
    def _convert_str_to_int(cls, value: str, info: ValidationInfo) -> str
        if not isinstance(value, str):
            raise ValueError(f"{info.field_name} must be a string!")  # TRY003 and TRY004
        
        return int(value)

Maybe some sort of allow list for TRY003 would be a nice idea, as for TRY004 I believe a way of understanding if it's a Pydantic validator or not would be ideal.

I am willing to help in any way I can, thanks for your time :)