PrimitiveDataclassMixin.from_primitive()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 13
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 11
dl 0
loc 13
ccs 0
cts 0
cp 0
rs 9.85
c 0
b 0
f 0
cc 1
nop 4
crap 2
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], *args, **kwargs) -> Any:
59
    kwargs = {
60
      key: cls._value_from_primitive(
61
        value=value[key],
62
        type_=field.type,
63
        *args,
64
        **kwargs
65
      )
66
      for key, field in cls.__dataclass_fields__.items()
67
      if field.init
68
    }
69
    return cls(**kwargs)
70
71
  @staticmethod
72
  def _value_from_primitive(value: Any, type_: type, *args, **kwargs) -> Any:
73
    if value is None:
74
      return
75
76
    if isinstance(value, type_):
77
      return value
78
79
    if hasattr(type_, "fromisoformat"):
80
      return type_.fromisoformat(value)
81
82
    if hasattr(type_, "from_primitive"):
83
      return type_.from_primitive(value, *args, **kwargs)
84
85
    return type_(value)
86