| Conditions | 4 |
| Total Lines | 22 |
| Code Lines | 14 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
| 1 | from typing import Dict |
||
| 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 |