Last active
May 27, 2022 20:42
-
-
Save a-recknagel/37328133cf44aa30c7f1dbb0edf4b3e0 to your computer and use it in GitHub Desktop.
pydantic validator example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
from pydantic import BaseModel, validator | |
class FirstLevel(BaseModel): | |
bar: "SecondLevel" | |
foo: int | |
@validator("foo") | |
def check_conditional_foo_values(cls, foo, values): | |
if values["bar"].baz == 2 and foo == 1: | |
raise ValueError(f"Can't have {foo=} if bar.baz={values['bar'].baz}.") | |
return foo # return new value for foo, in case you want to update it | |
class SecondLevel(BaseModel): | |
baz: int | |
FirstLevel.update_forward_refs() # necessary, because we are nesting models | |
a = json.loads("""{"foo": 2, "bar": {"baz": 2}}""") | |
b = json.loads("""{"foo": 1, "bar": {"baz": 2}}""") | |
FirstLevel(**a) # works | |
FirstLevel(**b) # crashes with a Pydantic error wrapping the ValueError |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment