jsons.serializers.default_tuple   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
eloc 19
dl 0
loc 42
rs 10
c 0
b 0
f 0

2 Functions

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