Completed
Push — master ( 5ea888...aa565f )
by Ramon
13s queued 11s
created

jsons.serializers.default_union   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 4
eloc 17
dl 0
loc 30
rs 10
c 0
b 0
f 0

1 Function

Rating   Name   Duplication   Size   Complexity  
A default_union_serializer() 0 22 4
1
from typing import Union
2
from jsons._common_impl import get_class_name
3
from jsons._compatibility_impl import get_union_params
4
from jsons._dump_impl import dump
5
from jsons.exceptions import JsonsError, SerializationError
6
7
8
def default_union_serializer(obj: object, cls: Union, **kwargs) -> object:
9
    """
10
    Serialize an object to any matching type of the given union. The first
11
    successful serialization is returned.
12
    :param obj: The object that is to be serialized.
13
    :param cls: The Union type with a generic (e.g. Union[str, int]).
14
    :param kwargs: Any keyword arguments that are passed through the
15
    serialization process.
16
    :return: An object of the first type of the Union that could be
17
    serialized successfully.
18
    """
19
    for sub_type in get_union_params(cls):
20
        try:
21
            return dump(obj, sub_type, **kwargs)
22
        except JsonsError:
23
            pass  # Try the next one.
24
    else:
25
        args_msg = ', '.join([get_class_name(cls_)
26
                              for cls_ in get_union_params(cls)])
27
        err_msg = ('Could not match the object of type "{}" to any type of '
28
                   'the Union: {}'.format(str(cls), args_msg))
29
        raise SerializationError(err_msg)
30