jsons._lizers_impl   A
last analyzed

Complexity

Total Complexity 22

Size/Duplication

Total Lines 160
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 22
eloc 81
dl 0
loc 160
rs 10
c 0
b 0
f 0

7 Functions

Rating   Name   Duplication   Size   Complexity  
A _get_parents() 0 17 4
A get_deserializer() 0 13 1
A _get_lizer_by_parents() 0 11 2
A set_serializer() 0 33 5
A set_deserializer() 0 34 5
A _get_lizer() 0 13 4
A get_serializer() 0 13 1
1
"""
2
PRIVATE MODULE: do not import (from) it directly.
3
4
This module contains functionality for setting and getting serializers and
5
deserializers.
6
"""
7
from typing import Optional, Dict, Sequence, Union
8
9
from jsons._cache import cached
10
from jsons._common_impl import StateHolder, get_class_name
11
from jsons._compatibility_impl import get_naked_class
12
13
14
def set_serializer(
15
        func: callable,
16
        cls: Union[type, Sequence[type]],
17
        high_prio: bool = True,
18
        fork_inst: type = StateHolder) -> None:
19
    """
20
    Set a serializer function for the given type. You may override the default
21
    behavior of ``jsons.load`` by setting a custom serializer.
22
23
    The ``func`` argument must take one argument (i.e. the object that is to be
24
    serialized) and also a ``kwargs`` parameter. For example:
25
26
    >>> def func(obj, **kwargs):
27
    ...    return dict()
28
29
    You may ask additional arguments between ``cls`` and ``kwargs``.
30
31
    :param func: the serializer function.
32
    :param cls: the type or sequence of types this serializer can handle.
33
    :param high_prio: determines the order in which is looked for the callable.
34
    :param fork_inst: if given, it uses this fork of ``JsonSerializable``.
35
    :return: None.
36
    """
37
    if isinstance(cls, Sequence):
38
        for cls_ in cls:
39
            set_serializer(func, cls_, high_prio, fork_inst)
40
    elif cls:
41
        index = 0 if high_prio else len(fork_inst._classes_serializers)
42
        fork_inst._classes_serializers.insert(index, cls)
43
        cls_name = get_class_name(cls, fully_qualified=True)
44
        fork_inst._serializers[cls_name.lower()] = func
45
    else:
46
        fork_inst._serializers['nonetype'] = func
47
48
49
def set_deserializer(
50
        func: callable,
51
        cls: Union[type, Sequence[type]],
52
        high_prio: bool = True,
53
        fork_inst: type = StateHolder) -> None:
54
    """
55
    Set a deserializer function for the given type. You may override the
56
    default behavior of ``jsons.dump`` by setting a custom deserializer.
57
58
    The ``func`` argument must take two arguments (i.e. the dict containing the
59
    serialized values and the type that the values should be deserialized into)
60
    and also a ``kwargs`` parameter. For example:
61
62
    >>> def func(dict_, cls, **kwargs):
63
    ...    return cls()
64
65
    You may ask additional arguments between ``cls`` and ``kwargs``.
66
67
    :param func: the deserializer function.
68
    :param cls: the type or sequence of types this serializer can handle.
69
    :param high_prio: determines the order in which is looked for the callable.
70
    :param fork_inst: if given, it uses this fork of ``JsonSerializable``.
71
    :return: None.
72
    """
73
    if isinstance(cls, Sequence):
74
        for cls_ in cls:
75
            set_deserializer(func, cls_, high_prio, fork_inst)
76
    elif cls:
77
        index = 0 if high_prio else len(fork_inst._classes_deserializers)
78
        fork_inst._classes_deserializers.insert(index, cls)
79
        cls_name = get_class_name(cls, fully_qualified=True)
80
        fork_inst._deserializers[cls_name.lower()] = func
81
    else:
82
        fork_inst._deserializers['nonetype'] = func
83
84
85
@cached
86
def get_serializer(
87
        cls: type,
88
        fork_inst: Optional[type] = StateHolder) -> callable:
89
    """
90
    Return the serializer function that would be used for the given ``cls``.
91
    :param cls: the type for which a serializer is to be returned.
92
    :param fork_inst: if given, it uses this fork of ``JsonSerializable``.
93
    :return: a serializer function.
94
    """
95
    serializer = _get_lizer(cls, fork_inst._serializers,
96
                            fork_inst._classes_serializers, fork_inst)
97
    return serializer
98
99
100
@cached
101
def get_deserializer(
102
        cls: type,
103
        fork_inst: Optional[type] = StateHolder) -> callable:
104
    """
105
    Return the deserializer function that would be used for the given ``cls``.
106
    :param cls: the type for which a deserializer is to be returned.
107
    :param fork_inst: if given, it uses this fork of ``JsonSerializable``.
108
    :return: a deserializer function.
109
    """
110
    deserializer = _get_lizer(cls, fork_inst._deserializers,
111
                              fork_inst._classes_deserializers, fork_inst)
112
    return deserializer
113
114
115
def _get_lizer(
116
        cls: type,
117
        lizers: Dict[str, callable],
118
        classes_lizers: list,
119
        fork_inst: type,
120
        recursive: bool = False) -> callable:
121
    cls_name = get_class_name(cls, str.lower, fully_qualified=True)
122
    lizer = (lizers.get(cls_name, None)
123
             or _get_lizer_by_parents(cls, lizers, classes_lizers, fork_inst))
124
    if not lizer and not recursive and hasattr(cls, '__supertype__'):
125
        return _get_lizer(cls.__supertype__, lizers,
126
                          classes_lizers, fork_inst, True)
127
    return lizer
128
129
130
def _get_lizer_by_parents(
131
        cls: type,
132
        lizers: Dict[str, callable],
133
        classes_lizers: list,
134
        fork_inst: type) -> callable:
135
    result = None
136
    parents = _get_parents(cls, classes_lizers)
137
    if parents:
138
        pname = get_class_name(parents[0], str.lower, fully_qualified=True)
139
        result = lizers[pname]
140
    return result
141
142
143
def _get_parents(cls: type, lizers: list) -> list:
144
    """
145
    Return a list of serializers or deserializers that can handle a parent
146
    of ``cls``.
147
    :param cls: the type that
148
    :param lizers: a list of serializers or deserializers.
149
    :return: a list of serializers or deserializers.
150
    """
151
    parents = []
152
    naked_cls = get_naked_class(cls)
153
    for cls_ in lizers:
154
        try:
155
            if issubclass(naked_cls, cls_):
156
                parents.append(cls_)
157
        except (TypeError, AttributeError):
158
            pass  # Some types do not support `issubclass` (e.g. Union).
159
    return parents
160