79120137

Date: 2024-10-24 01:19:07
Score: 2
Natty:
Report link

I don't know that there is a Pydantic way to specify the default value at validation time. However, if you don't want to modify the Thing class you could always subclass it in a private scope?

import pydantic


class Thing(pydantic.BaseModel):
    one: int
    two: str
    three: bool


def validate(data: dict[str, dict]):

    class _Thing(Thing):
        three: str = True

    adapter = pydantic.TypeAdapter(dict[str, _Thing])
    adapter.validate_python(data)


raw_data = {"this": {"one": 1, "two": "zwei"}, "that": {"one": 111, "two": "dos"}}
validate(raw_data)
Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Ends in question mark (2):
  • Low reputation (1):
Posted by: Zac Scott