Passed
Pull Request — master (#180)
by
unknown
01:17
created

jsons.deserializers.default_literal   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 26
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
eloc 12
dl 0
loc 26
rs 10
c 0
b 0
f 0

1 Function

Rating   Name   Duplication   Size   Complexity  
B default_literal_deserializer() 0 21 6
1
from typing import Literal, Any, get_args
2
3
from jsons.exceptions import DeserializationError
4
5
def default_literal_deserializer(obj: Any, cls: Literal, *, strictly_equal_literal: bool = False, **_):
6
    """
7
    Deserialize an object to any matching value of the given Literal. The first
8
    successful deserialization is returned.
9
    :param obj: The object that needs deserializing.
10
    :param cls: The Literal type with values (e.g. Literal[1, 2]).
11
    :param strictly_equal_literal: determines whether the type of the value
12
    and literal should also be taken into account.
13
    :param _: not used.
14
    :return: An object of the first value of the Literal that could be
15
    deserialized successfully.
16
    """
17
    for literal_value in get_args(cls):
18
        value_equal = obj == literal_value
19
        type_equal = type(obj) == type(literal_value)
20
        if value_equal and (not strictly_equal_literal or type_equal):
21
            break
22
    else:
23
        err_msg = 'Could not match the object "{}" to the Literal: {}'.format(obj, cls)
24
        raise DeserializationError(err_msg, obj, None)
25
    return literal_value
26