Repository navigation
Expand file tree
/
Copy pathcompat.py
More file actions
79 lines (60 loc) · 2.18 KB
/
Copy pathcompat.py
File metadata and controls
79 lines (60 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# flake8: noqa
from functools import lru_cache
from typing import Any, Dict, Optional, Type, TypeVar, Union
import pydantic
from importlib_metadata import version
from packaging.version import Version, parse
PYDANTIC_VER = parse(version("pydantic"))
Model = TypeVar("Model", bound="pydantic.BaseModel")
IS_PYDANTIC2 = PYDANTIC_VER >= Version("2.0")
if IS_PYDANTIC2:
T = TypeVar("T")
@lru_cache()
def create_type_adapter(annot: T) -> pydantic.TypeAdapter[T]:
return pydantic.TypeAdapter(annot)
def parse_obj_as(annot: T, obj: Any) -> T:
return create_type_adapter(annot).validate_python(obj)
def model_validate(
model_class: Type[Model],
message: Dict[str, Any],
) -> Model:
return model_class.model_validate(message)
def model_dump(instance: Model) -> Dict[str, Any]:
return instance.model_dump(mode="json")
def model_validate_json(
model_class: Type[Model],
message: Union[str, bytes, bytearray],
) -> Model:
return model_class.model_validate_json(message)
def model_dump_json(instance: Model) -> str:
return instance.model_dump_json()
def model_copy(
instance: Model,
update: Optional[Dict[str, Any]] = None,
deep: bool = False,
) -> Model:
return instance.model_copy(update=update, deep=deep)
validate_call = pydantic.validate_call
else:
parse_obj_as = pydantic.parse_obj_as # type: ignore
def model_validate(
model_class: Type[Model],
message: Dict[str, Any],
) -> Model:
return model_class.parse_obj(message)
def model_dump(instance: Model) -> Dict[str, Any]:
return instance.dict()
def model_validate_json(
model_class: Type[Model],
message: Union[str, bytes, bytearray],
) -> Model:
return model_class.parse_raw(message)
def model_dump_json(instance: Model) -> str:
return instance.json()
def model_copy(
instance: Model,
update: Optional[Dict[str, Any]] = None,
deep: bool = False,
) -> Model:
return instance.copy(update=update, deep=deep)
validate_call = pydantic.validate_arguments # type: ignore