1- from typing import Any , Dict , Type , TypeVar
1+ from typing import Any , Dict , Generic , Type , TypeVar
22
33from pydantic import BaseModel
44from pydantic .version import VERSION as PYDANTIC_VERSION
77PYDANTIC_V2 = PYDANTIC_VERSION_MINOR_TUPLE [0 ] == 2
88
99
10+ T = TypeVar ("T" )
1011Model = TypeVar ("Model" , bound = BaseModel )
1112
1213
@@ -22,3 +23,40 @@ def model_validate_json(model_class: Type[Model], data: str) -> Model:
2223 return model_class .model_validate_json (data ) # type: ignore[no-any-return, unused-ignore, attr-defined]
2324 else :
2425 return model_class .parse_raw (data ) # type: ignore[no-any-return, unused-ignore, attr-defined]
26+
27+
28+ def model_dump (obj : BaseModel , ** kwargs : Any ) -> Dict [Any , Any ]:
29+ if PYDANTIC_V2 :
30+ return obj .model_dump (** kwargs ) # type: ignore[no-any-return, unused-ignore, attr-defined]
31+ else :
32+ return obj .dict (** kwargs ) # type: ignore[no-any-return, unused-ignore, attr-defined]
33+
34+
35+ def model_dump_json (obj : BaseModel ) -> str :
36+ if PYDANTIC_V2 :
37+ return obj .model_dump_json () # type: ignore[no-any-return, unused-ignore, attr-defined]
38+ else :
39+ return obj .json () # type: ignore[no-any-return, unused-ignore, attr-defined]
40+
41+
42+ class TypeAdapter (Generic [T ]):
43+ def __init__ (self , type_ : Type [T ]) -> None :
44+ self .type_ = type_
45+
46+ if PYDANTIC_V2 :
47+ from pydantic import ( # type: ignore[attr-defined, unused-ignore]
48+ TypeAdapter as PydanticTypeAdapter ,
49+ )
50+
51+ self ._adapter = PydanticTypeAdapter (type_ )
52+ else :
53+ self ._adapter = None # type: ignore[assignment, unused-ignore]
54+
55+ def validate_python (self , value : Any ) -> T :
56+ """Validate a Python object against the type."""
57+ if PYDANTIC_V2 :
58+ return self ._adapter .validate_python (value ) # type: ignore[no-any-return, union-attr, unused-ignore]
59+ else :
60+ from pydantic import parse_obj_as
61+
62+ return parse_obj_as (self .type_ , value ) # type: ignore[no-any-return, unused-ignore]
0 commit comments