1
|
|
|
from typing import Union, Optional, Tuple |
2
|
|
|
|
3
|
|
|
from typish import get_args |
4
|
|
|
|
5
|
|
|
from jsons._compatibility_impl import tuple_with_ellipsis |
6
|
|
|
from jsons._dump_impl import dump |
7
|
|
|
from jsons.serializers.default_iterable import default_iterable_serializer |
8
|
|
|
|
9
|
|
|
|
10
|
|
|
def default_tuple_serializer(obj: tuple, |
11
|
|
|
cls: Optional[type] = None, |
12
|
|
|
**kwargs) -> Union[list, dict]: |
13
|
|
|
""" |
14
|
|
|
Serialize the given ``obj`` to a list of serialized objects. |
15
|
|
|
:param obj: the tuple that is to be serialized. |
16
|
|
|
:param cls: the type of the ``obj``. |
17
|
|
|
:param kwargs: any keyword arguments that may be given to the serialization |
18
|
|
|
process. |
19
|
|
|
:return: a list of which all elements are serialized. |
20
|
|
|
""" |
21
|
|
|
if hasattr(obj, '_fields'): |
22
|
|
|
return default_namedtuple_serializer(obj, **kwargs) |
23
|
|
|
|
24
|
|
|
cls_ = cls |
25
|
|
|
if cls and tuple_with_ellipsis(cls): |
26
|
|
|
cls_ = Tuple[(get_args(cls)[0],) * len(obj)] |
27
|
|
|
|
28
|
|
|
return default_iterable_serializer(obj, cls_, **kwargs) |
29
|
|
|
|
30
|
|
|
|
31
|
|
|
def default_namedtuple_serializer(obj: tuple, **kwargs) -> dict: |
32
|
|
|
""" |
33
|
|
|
Serialize the given ``obj`` to a dict of serialized objects. |
34
|
|
|
:param obj: the named tuple that is to be serialized. |
35
|
|
|
:param kwargs: any keyword arguments that may be given to the serialization |
36
|
|
|
process. |
37
|
|
|
:return: a dict of which all elements are serialized. |
38
|
|
|
""" |
39
|
|
|
result = {field_name: dump(getattr(obj, field_name), **kwargs) |
40
|
|
|
for field_name in obj._fields} |
41
|
|
|
return result |
42
|
|
|
|