Completed
Pull Request — master (#27)
by Ramon
01:10
created

default_namedtuple_serializer()   A

Complexity

Conditions 1

Size

Total Lines 11
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 11
rs 10
c 0
b 0
f 0
cc 1
nop 2
1
from typing import Union
2
from jsons._main_impl import dump
3
from jsons.serializers.default_iterable import default_iterable_serializer
4
5
6
def default_tuple_serializer(obj: tuple, **kwargs) -> Union[list, dict]:
7
    """
8
    Serialize the given ``obj`` to a list of serialized objects.
9
    :param obj: the tuple that is to be serialized.
10
    :param kwargs: any keyword arguments that may be given to the serialization
11
    process.
12
    :return: a list of which all elements are serialized.
13
    """
14
    if hasattr(obj, '_fields'):
15
        return default_namedtuple_serializer(obj, **kwargs)
16
    return default_iterable_serializer(obj, **kwargs)
17
18
19
def default_namedtuple_serializer(obj: tuple, **kwargs) -> dict:
20
    """
21
    Serialize the given ``obj`` to a dict of serialized objects.
22
    :param obj: the named tuple that is to be serialized.
23
    :param kwargs: any keyword arguments that may be given to the serialization
24
    process.
25
    :return: a dict of which all elements are serialized.
26
    """
27
    result = {field_name: dump(getattr(obj, field_name), **kwargs)
28
              for field_name in obj._fields}
29
    return result
30