[Python] Set initial value of a Pydantic 2 field using validator

Discussão em 'Python' iniciado por Stack, Março 21, 2025.

  1. Stack

    Stack Membro Participativo

    Say I have the following Pydantic 2.10.6 model, where x is dynamically calculated from another field, y:

    from pydantic import BaseModel, Field, field_validator, ValidationInfo

    class Foo(BaseModel):
    x: int = Field(init=False)
    y: int

    @field_validator("x", mode="before")
    @staticmethod
    def set_x(val: None, info: ValidationInfo):
    return info.data["y"] + 1

    Foo(y=1)


    Running this as is fails validation:

    pydantic_core._pydantic_core.ValidationError: 1 validation error for Foo
    x
    Field required [type=missing, input_value={'y': 1}, input_type=dict]


    I can "fix" the runtime error by giving x a default:

    x: int = Field(init=False, default=None)


    But then this fails type checking in pyright with:

    Type "None" is not assignable to declared type "int"


    I can also fix it using a model_validator, but this is a tad less neat:

    from pydantic import BaseModel, Field, model_validator

    class Foo(BaseModel):
    x: int = Field(init=False)
    y: int

    @model_validator(mode="before")
    @staticmethod
    def set_x(data: dict):
    data["x"] = data["y"] + 1
    return data

    Foo(y=1)


    How can I cleanly represent this model using only a field validator?

    Continue reading...

Compartilhe esta Página