Passed
Pull Request — master (#17)
by Ramon
50s
created

jsons.deserializers.default_union   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 28
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 4
eloc 15
dl 0
loc 28
rs 10
c 0
b 0
f 0

1 Function

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