[Python] Pydantic validations for extra fields that not defined in schema

Discussão em 'Python' iniciado por Stack, Abril 22, 2025.

  1. Stack

    Stack Membro Participativo

    I am using pydantic for schema validations and I would like to throw an error when any extra field that isn't defined is added to a schema.

    from typing import Literal, Union

    from pydantic import BaseModel, Field, ValidationError


    class Cat(BaseModel):
    pet_type: Literal['cat']
    meows: int


    class Dog(BaseModel):
    pet_type: Literal['dog']
    barks: float


    class Lizard(BaseModel):
    pet_type: Literal['reptile', 'lizard']
    scales: bool


    class Model(BaseModel):
    pet: Union[Cat, Dog, Lizard] = Field(..., discriminator='pet_type')
    n: int


    print(Model(pet={'pet_type': 'dog', 'barks': 3.14, 'eats': 'biscuit'}, n=1))
    """ try:
    Model(pet={'pet_type': 'dog'}, n=1)
    except ValidationError as e:
    print(e) """



    In the above code, I have added the eats field which is not defined. The pydantic validations are applied and the extra values that I defined are removed in response. I want to throw an error saying eats is not allowed for Dog or something like that. Is there any way to achieve that?

    And is there any chance that we can provide the input directly instead of the pet object?
    print(Model({'pet_type': 'dog', 'barks': 3.14, 'eats': 'biscuit', n=1})). I tried without descriminator but those specific validations are missing related to pet_type. Can someone guide me how to achieve either one of that?

    Continue reading...

Compartilhe esta Página