Passed
Pull Request — master (#68)
by
unknown
01:35
created

default_complex_deserializer()   A

Complexity

Conditions 4

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

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