python - Set initial value of a Pydantic 2 field using validator - Stack Overflow

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

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?

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744369146a4570861.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信