jsons.deserializers.default_union   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Importance

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

1 Function

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