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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay