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?

2
  • 2
    Does x have to be a regular field then? If you are initializing it from y, why not using a computed_field? Commented Mar 21 at 8:49
  • Btw, with a model_validator(mode="before") it works. Commented Mar 21 at 8:58

1 Answer 1

1

as @lord_haffi said, you can use computed fields in pydantic. Given your example, you would have:

from pydantic import BaseModel, computed_field

class Foo(BaseModel):
    y: int

    @computed_field
    @property
    def x(self) -> int:
        return self.y + 1

Foo(y=1)
# Foo(y=1, x=2)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.