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

jsons.serializers.default_tuple   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 3
eloc 12
dl 0
loc 30
rs 10
c 0
b 0
f 0

2 Functions

Rating   Name   Duplication   Size   Complexity  
A default_tuple_serializer() 0 11 2
A default_namedtuple_serializer() 0 11 1
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