[Python] How to drop discriminator value from loc in validation error?

Discussão em 'Python' iniciado por Stack, Setembro 29, 2024.

  1. Stack

    Stack Membro Participativo

    I use Pydantic v2. For now I'd like to remove discriminator value from loc or validation error. Please take a look at the code below:

    from pprint import pprint
    from typing import Literal, Union, Annotated, Any

    from pydantic import BaseModel, Field, RootModel, ValidationError
    from pydantic.main import Model


    class Tiger(BaseModel):
    animal_type: Literal["tiger"] = "tiger"
    ferocity_scale: float = Field(..., ge=0, le=10)


    class Shark(BaseModel):
    animal_type: Literal["shark"] = "shark"
    ferocity_scale: float = Field(..., ge=0, le=10)


    class Lion(BaseModel):
    animal_type: Literal["lion"] = "lion"
    ferocity_scale: float


    class WildAnimal(RootModel):
    root: Annotated[Union[Tiger, Shark, Lion], Field(..., discriminator='animal_type')]


    try:
    my_shark = WildAnimal.model_validate({'animal_type': 'shark', 'ferocity_scale': 115})
    except ValidationError as exc:
    pprint(exc.errors())


    The code prints:

    [{'ctx': {'le': 10.0},
    'input': 115,
    'loc': ('shark', 'ferocity_scale'), <------ how to drop "shark"?
    'msg': 'Input should be less than or equal to 10',
    'type': 'less_than_equal',
    'url': 'https://errors.pydantic.dev/2.7/v/less_than_equal'}]


    In loc key you could notice ('shark', 'ferocity_scale'). The value shark is the discriminator animal_type value.

    How to drop it by means of Pydantic? Or how to detect dynamically that the first value of loc is discriminator value?

    The only thing I could figure out:

    class WildAnimal(RootModel):
    root: Annotated[Union[Tiger, Shark, Lion], Field(..., discriminator='animal_type')]

    @classmethod
    def model_validate(cls: type[Model], obj: Any, *, strict: bool | None = None, from_attributes: bool | None = None,
    context: dict[str, Any] | None = None) -> Model:
    try:
    return super().model_validate(obj, strict=strict, from_attributes=from_attributes, context=context)
    except ValidationError as exc:
    # modify loc
    # reraise ValidationError

    Continue reading...

Compartilhe esta Página