Completed
Push — master ( bf8671...1ef08e )
by Ramon
28s queued 12s
created

default_list_serializer()   A

Complexity

Conditions 4

Size

Total Lines 39
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 21
dl 0
loc 39
rs 9.376
c 0
b 0
f 0
cc 4
nop 6
1
from typing import Optional
2
3
from typish import get_args
4
5
from jsons import get_serializer
6
from jsons._common_impl import StateHolder
7
from jsons._dump_impl import dump
8
9
10
def default_list_serializer(
11
        obj: list,
12
        cls: type = None,
13
        *,
14
        strict: bool = False,
15
        fork_inst: Optional[type] = StateHolder,
16
        **kwargs) -> list:
17
    """
18
    Serialize the given ``obj`` to a list of serialized objects.
19
    :param obj: the list that is to be serialized.
20
    :param cls: the (subscripted) type of the list.
21
    :param strict: a bool to determine if the serializer should be strict
22
    (i.e. only dumping stuff that is known to ``cls``).
23
    :param fork_inst: if given, it uses this fork of ``JsonSerializable``.
24
    :param kwargs: any keyword arguments that may be given to the serialization
25
    process.
26
    :return: a list of which all elements are serialized.
27
    """
28
    if not obj:
29
        return []
30
31
    kwargs_ = {**kwargs, 'strict': strict}
32
33
    # The meta kwarg store_cls is filtered out, because an iterable should have
34
    # its own -meta attribute.
35
    kwargs_.pop('_store_cls', None)
36
37
    inner_type = None
38
    serializer = dump
39
40
    cls_args = get_args(cls)
41
    if cls_args:
42
        inner_type = cls_args[0]
43
        serializer = get_serializer(inner_type, fork_inst)
44
    elif strict:
45
        inner_type = type(obj[0])
46
        serializer = get_serializer(inner_type, fork_inst)
47
48
    return [serializer(elem, cls=inner_type, fork_inst=fork_inst, **kwargs_) for elem in obj]
49