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

Top comments (0)