[Python] Python Pydantic `TypeAdapter` validate with default for missing attribute

Discussão em 'Python' iniciado por Stack, Outubro 24, 2024.

  1. Stack

    Stack Membro Participativo

    Suppose I have:

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

    adapter = pydantic.TypeAdapter(dict[str, Thing])

    raw_data = {"this": {"one": 1, "two": "zwei"}, "that": {"one": 111, "two": "dos"}}


    You can see that the raw_data, which I want to convert (validate) using adapter, contains two items that are missing the attribute three. I want to be able to still validate this, but give it a default value True for the missing attribute three. However, I don't want to do this in the definition of class Thing, because in my use-case this default behaviour is not an intrinsic part of the class Thing. I don't want users of this class to assume there's always a default for the attribute three; I only want to provide a default value this time only, for this particular raw_data only, because I'm expecting this particular raw_data to be missing three for some reason. (In particular, this question looks similar but does not solve my problem.) So, what I want is something like:

    things_i_want = adapter.validate_python(raw_data, default={"three": True})


    Or:

    or_this = adapter.validate_python(raw_data, default=pydantic.Default(three=True))


    Is this possible at all in Pydantic?

    Continue reading...

Compartilhe esta Página