最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin5浏览0评论

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?

发布评论

评论列表(0)

  1. 暂无评论