Skip to content

Instantly share code, notes, and snippets.

@a-recknagel
Last active May 27, 2022 20:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save a-recknagel/37328133cf44aa30c7f1dbb0edf4b3e0 to your computer and use it in GitHub Desktop.
Save a-recknagel/37328133cf44aa30c7f1dbb0edf4b3e0 to your computer and use it in GitHub Desktop.
pydantic validator example
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