Completed
Push — master ( 6c485c...cd3e21 )
by Ramon
12s queued 10s
created

default_complex_deserializer()   A

Complexity

Conditions 3

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 22
rs 9.75
c 0
b 0
f 0
cc 3
nop 3
1
from typing import Dict
2
3
from jsons.exceptions import DeserializationError
4
from jsons._load_impl import load
5
6
7
def default_complex_deserializer(obj: Dict[str, float],
8
                                 cls: type = complex,
9
                                 **kwargs) -> complex:
10
    """
11
    Deserialize a dictionary with 'real' and 'imag' keys to a complex number.
12
    :param obj: the dict that is to be deserialized.
13
    :param cls: not used.
14
    :param kwargs: not used.
15
    :return: an instance of ``complex``.
16
    """
17
    try:
18
        clean_obj = load({'real': obj['real'], 'imag': obj['imag']},
19
                         cls=Dict[str, float])
20
        return complex(clean_obj['real'], clean_obj['imag'])
21
    except KeyError as err:
22
        raise AttributeError("Cannot deserialize {} to a complex number, "
23
                             "does not contain key '{}'"
24
                             .format(obj, err.args[0]))
25
    except DeserializationError as err:
26
        raise AttributeError("Cannot deserialize {} to a complex number, "
27
                             "cannot cast value {} to float"
28
                             .format(obj, err.source))
29