File: entities.py

package info (click to toggle)
python-mashumaro 3.16-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,400 kB
  • sloc: python: 19,890; sh: 16; makefile: 5
file content (296 lines) | stat: -rw-r--r-- 6,165 bytes parent folder | download
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
from collections import namedtuple
from dataclasses import dataclass
from datetime import date, datetime
from enum import Enum, Flag, IntEnum, IntFlag
from os import PathLike
from typing import Any, Generic, List, NewType, Optional, Union

try:
    from enum import StrEnum
except ImportError:  # pragma: no cover

    class StrEnum(str, Enum):
        pass


from typing_extensions import NamedTuple, ReadOnly, TypedDict, TypeVar

from mashumaro import DataClassDictMixin
from mashumaro.config import TO_DICT_ADD_OMIT_NONE_FLAG, BaseConfig
from mashumaro.types import GenericSerializableType, SerializableType

T = TypeVar("T")
TAny = TypeVar("TAny", bound=Any)
TInt = TypeVar("TInt", bound=int)
TDefaultInt = TypeVar("TDefaultInt", default=int)
TIntStr = TypeVar("TIntStr", int, str)
T_Optional_int = TypeVar("T_Optional_int", bound=Optional[int])


class MyEnum(Enum):
    a = "letter a"
    b = "letter b"


class MyStrEnum(str, Enum):
    a = "letter a"
    b = "letter b"


class MyNativeStrEnum(StrEnum):
    a = "letter a"
    b = "letter b"


class MyIntEnum(IntEnum):
    a = 1
    b = 2


class MyFlag(Flag):
    a = 1
    b = 2


class MyIntFlag(IntFlag):
    a = 1
    b = 2


class MyList(list):
    pass


@dataclass
class MyDataClass(DataClassDictMixin):
    a: int
    b: int


@dataclass(frozen=True)
class MyFrozenDataClass:
    x: int


class MutableString(SerializableType):
    def __init__(self, value: str):
        self.characters = [c for c in value]

    def _serialize(self) -> str:
        return str(self)

    @classmethod
    def _deserialize(cls, value: str) -> "MutableString":
        return MutableString(value)

    def __str__(self):
        return "".join(self.characters)

    def __eq__(self, other):
        return self.characters == other.characters


class GenericSerializableList(Generic[T], GenericSerializableType):
    def __init__(self, value: List[T]):
        self.value = value

    def _serialize(self, types):
        if types[0] == int:
            return [v + 2 for v in self.value]
        elif types[0] == str:
            return [f"_{v}" for v in self.value]

    @classmethod
    def _deserialize(cls, value, types):
        if types[0] == int:
            return GenericSerializableList([int(v) - 2 for v in value])
        elif types[0] == str:
            return GenericSerializableList([v[1:] for v in value])

    def __eq__(self, other):
        return self.value == other.value


class GenericSerializableWrapper(Generic[T], GenericSerializableType):
    def __init__(self, value: T):
        self.value = value

    def _serialize(self, types):
        if types[0] == date:
            return self.value.isoformat()

    @classmethod
    def _deserialize(cls, value, types):
        if types[0] == date:
            return GenericSerializableWrapper(date.fromisoformat(value))

    def __eq__(self, other):
        return self.value == other.value


class CustomPath(PathLike):
    def __init__(self, *args: str):
        self._path = "/".join(args)

    def __fspath__(self):
        return self._path

    def __eq__(self, other):
        return isinstance(other, CustomPath) and self._path == other._path


@dataclass
class MyDataClassWithUnion(DataClassDictMixin):
    a: Union[int, str]
    b: Union[MyEnum, int]


@dataclass
class MyDataClassWithOptional(DataClassDictMixin):
    a: Optional[int] = None
    b: Optional[int] = None


@dataclass
class MyDataClassWithOptionalAndOmitNoneFlag(DataClassDictMixin):
    a: Optional[int] = None
    b: Optional[int] = None

    class Config(BaseConfig):
        code_generation_options = [TO_DICT_ADD_OMIT_NONE_FLAG]


class ThirdPartyType:
    def __init__(self, value):
        self.value = value

    def __eq__(self, other):
        return isinstance(other, ThirdPartyType) and self.value == other.value


@dataclass
class DataClassWithoutMixin:
    i: int


@dataclass
class SerializableTypeDataClass(SerializableType):
    a: int
    b: int

    def _serialize(self):
        return {"a": self.a + 1, "b": self.b + 1}

    @classmethod
    def _deserialize(cls, value):
        a = value.get("a") - 1
        b = value.get("b") - 1
        return cls(a, b)


@dataclass
class GenericSerializableTypeDataClass(GenericSerializableType):
    a: int
    b: int

    def _serialize(self, types):
        return {"a": self.a + 1, "b": self.b + 1}

    @classmethod
    def _deserialize(cls, value, types):
        a = value.get("a") - 1
        b = value.get("b") - 1
        return cls(a, b)


@dataclass
class MyGenericDataClass(Generic[T], DataClassDictMixin):
    x: T


class MyGenericList(List[T]):
    pass


class SerializableTypeGenericList(Generic[T], SerializableType):
    def __init__(self, value: List[T]):
        self.value = value

    def _serialize(self):
        return self.value

    @classmethod
    def _deserialize(cls, value):
        return SerializableTypeGenericList(value)

    def __eq__(self, other):
        return self.value == other.value


TMyDataClass = TypeVar("TMyDataClass", bound=MyDataClass)


class TypedDictRequiredKeys(TypedDict):
    int: int
    float: float


class TypedDictOptionalKeys(TypedDict, total=False):
    int: int
    float: float


class TypedDictRequiredAndOptionalKeys(TypedDictRequiredKeys, total=False):
    str: str


class TypedDictRequiredKeysWithOptional(TypedDict):
    x: Optional[int]
    y: int


class TypedDictOptionalKeysWithOptional(TypedDict, total=False):
    x: Optional[int]
    y: float


class TypedDictWithReadOnly(TypedDict):
    x: ReadOnly[int]


class GenericTypedDict(TypedDict, Generic[T]):
    x: T
    y: int


class MyNamedTuple(NamedTuple):
    i: int
    f: float


class MyNamedTupleWithDefaults(NamedTuple):
    i: int = 1
    f: float = 2.0


class MyNamedTupleWithOptional(NamedTuple):
    i: Optional[int]
    f: int


MyUntypedNamedTuple = namedtuple("MyUntypedNamedTuple", ("i", "f"))


MyUntypedNamedTupleWithDefaults = namedtuple(
    "MyUntypedNamedTupleWithDefaults",
    ("i", "f"),
    defaults=(1, 2.0),
)


class GenericNamedTuple(NamedTuple, Generic[T]):
    x: T
    y: int


MyDatetimeNewType = NewType("MyDatetimeNewType", datetime)