| Total Complexity | 3 |
| Total Lines | 29 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 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 |