Completed
Pull Request — master (#68)
by
unknown
01:04
created

jsons.deserializers.default_complex   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 26
Duplicated Lines 0 %

Importance

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

1 Function

Rating   Name   Duplication   Size   Complexity  
A default_complex_deserializer() 0 22 4
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("Cannot deserialize {} to a complex number, does not contain key '{}'".format(obj, key))
20
        try:
21
            float(value)
22
        except TypeError:
23
            raise AttributeError("Cannot deserialize {} to a complex number, can't cast value of '{}' to float".format(obj, key))
24
25
    return complex(real, imag)
26