| Conditions | 6 |
| Total Lines | 21 |
| Code Lines | 9 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
| 1 | from typing import Literal, Any, get_args |
||
| 5 | def default_literal_deserializer(obj: Any, cls: Literal, *, strictly_equal_literal: bool = False, **_): |
||
| 6 | """ |
||
| 7 | Deserialize an object to any matching value of the given Literal. The first |
||
| 8 | successful deserialization is returned. |
||
| 9 | :param obj: The object that needs deserializing. |
||
| 10 | :param cls: The Literal type with values (e.g. Literal[1, 2]). |
||
| 11 | :param strictly_equal_literal: determines whether the type of the value |
||
| 12 | and literal should also be taken into account. |
||
| 13 | :param _: not used. |
||
| 14 | :return: An object of the first value of the Literal that could be |
||
| 15 | deserialized successfully. |
||
| 16 | """ |
||
| 17 | for literal_value in get_args(cls): |
||
| 18 | value_equal = obj == literal_value |
||
| 19 | type_equal = type(obj) == type(literal_value) |
||
| 20 | if value_equal and (not strictly_equal_literal or type_equal): |
||
| 21 | break |
||
| 22 | else: |
||
| 23 | err_msg = 'Could not match the object "{}" to the Literal: {}'.format(obj, cls) |
||
| 24 | raise DeserializationError(err_msg, obj, None) |
||
| 25 | return literal_value |
||
| 26 |