DEV Community

Gurpinder Singh
Gurpinder Singh

Posted on

How to build a class variable after validation based on the parsed input using pydantic V2?

In Pydantic, you can use the @validator decorator to create a validation function for your class, and set the pre argument to True to ensure that the validation function runs before the values are assigned to the fields. Here's an example of how you can achieve what you want:

from pydantic import BaseModel, validator

class Thermopotentiostat(BaseModel):
    foo: int
    bar: int
    baz: int

    @validator("baz", pre=True, always=True)
    def calculate_baz(cls, value, values):
        foo = values.get("foo")
        bar = values.get("bar")
        if foo is not None and bar is not None:
            return foo * bar
        return value

# Example usage
thermo = Thermopotentiostat(foo=2, bar=3)
print(thermo.dict())
print(thermo.baz)

Enter fullscreen mode Exit fullscreen mode

In this example, the calculate_baz validator function is executed before the values are assigned to the fields (pre=True). The always=True ensures that the validation function is always called, even if one of the fields is missing. Inside the validator, it retrieves the values of foo and bar and calculates the value for baz.

Now, when you create an instance of Thermopotentiostat, the baz field will be calculated based on the provided values for foo and bar. The baz field is not part of the class signature, but it is available as an attribute after instantiation.

Thanks for reading,
More solutions available at DGI Host.com

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more