1
|
1 |
|
import dataclasses |
2
|
1 |
|
import sys |
3
|
|
|
|
4
|
1 |
|
if sys.version_info >= (3, 9): |
5
|
1 |
|
Dict = dict |
6
|
1 |
|
else: |
7
|
|
|
from typing import Dict |
8
|
1 |
|
|
9
|
|
|
from collections import UserString |
10
|
|
|
|
11
|
1 |
|
from typing import Any |
12
|
|
|
from typing import ClassVar |
13
|
|
|
from typing import Optional |
14
|
|
|
|
15
|
|
|
from .typing import String |
16
|
1 |
|
|
17
|
1 |
|
from ._utils import export |
18
|
|
|
|
19
|
1 |
|
|
20
|
1 |
|
@export |
21
|
|
|
@dataclasses.dataclass(frozen=True) |
22
|
|
|
class VerboseDataclassMixin: |
23
|
|
|
verbose_name: ClassVar[String] = dataclasses.field( |
24
|
1 |
|
init=False, |
25
|
1 |
|
) |
26
|
1 |
|
help_text: ClassVar[Optional[String]] = dataclasses.field( |
27
|
|
|
init=False, |
28
|
|
|
default=None, |
29
|
|
|
) |
30
|
|
|
|
31
|
1 |
|
|
32
|
1 |
|
@export |
33
|
1 |
|
class PrimitiveDataclassMixin: |
34
|
1 |
|
|
35
|
1 |
|
def to_primitive(self, *args, **kwargs) -> Dict[str, Any]: |
36
|
1 |
|
return { |
37
|
|
|
key: self._value_to_primitive(getattr(self, key), *args, **kwargs) |
38
|
1 |
|
for key in self.__dataclass_fields__.keys() |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
@staticmethod |
42
|
|
|
def _value_to_primitive(value: Any, *args, **kwargs) -> Any: |
43
|
|
|
if value is None: |
44
|
|
|
return |
45
|
|
|
|
46
|
|
|
if hasattr(value, "to_primitive"): |
47
|
|
|
return value.to_primitive(*args, **kwargs) |
48
|
|
|
|
49
|
|
|
if hasattr(value, "isoformat"): |
50
|
|
|
return value.isoformat() |
51
|
|
|
|
52
|
|
|
if isinstance(value, UserString): |
53
|
|
|
return str(value) |
54
|
|
|
|
55
|
|
|
return value |
56
|
|
|
|
57
|
|
|
@classmethod |
58
|
|
|
def from_primitive(cls, value: Dict[str, Any]) -> Any: |
59
|
|
|
kwargs = { |
60
|
|
|
key: cls._value_from_primitive( |
61
|
|
|
value=value[key], |
62
|
|
|
type_=field.type, |
63
|
|
|
) |
64
|
|
|
for key, field in cls.__dataclass_fields__.items() |
65
|
|
|
if field.init |
66
|
|
|
} |
67
|
|
|
return cls(**kwargs) |
68
|
|
|
|
69
|
|
|
@staticmethod |
70
|
|
|
def _value_from_primitive(value: Any, type_: type) -> Any: |
71
|
|
|
if value is None: |
72
|
|
|
return |
73
|
|
|
|
74
|
|
|
if isinstance(value, type_): |
75
|
|
|
return value |
76
|
|
|
|
77
|
|
|
if hasattr(type_, "fromisoformat"): |
78
|
|
|
return type_.fromisoformat(value) |
79
|
|
|
|
80
|
|
|
if hasattr(type_, "from_primitive"): |
81
|
|
|
return type_.from_primitive(value) |
82
|
|
|
|
83
|
|
|
return type_(value) |
84
|
|
|
|