[Python] How do conditionally apply field constraints based on value type in pydantic v2?

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

  1. Stack

    Stack Membro Participativo

    I have this pydantic model with a field, and this field could be either an int or a non numeric value like a str or list.

    from pydantic import BaseModel, Field

    class Foo(BaseModel):
    bar: str | list | int = Field('some string', ge=2)


    I want it to be that the constraint ge=2 is applied only if the value given to bar happens to be an int.

    foo_instance = Foo(bar='asdf') # constraint should not be applied
    foo_instance = Foo(bar=4) # constraint should be applied


    Trying the above throws an error: TypeError: Unable to apply constraint 'ge' to supplied value asdf

    How do I ensure pydantic only tries to apply this constraint if the value is numerical (or if the operation can be performed on this value)?

    Continue reading...

Compartilhe esta Página