| Total Complexity | 4 |
| Total Lines | 31 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 1 | from typing import Union |
||
| 2 | |||
| 3 | from jsons._common_impl import get_class_name |
||
| 4 | from jsons._compatibility_impl import get_union_params |
||
| 5 | from jsons._load_impl import load |
||
| 6 | from jsons.exceptions import JsonsError, DeserializationError |
||
| 7 | |||
| 8 | |||
| 9 | def default_union_deserializer(obj: object, cls: Union, **kwargs) -> object: |
||
| 10 | """ |
||
| 11 | Deserialize an object to any matching type of the given union. The first |
||
| 12 | successful deserialization is returned. |
||
| 13 | :param obj: The object that needs deserializing. |
||
| 14 | :param cls: The Union type with a generic (e.g. Union[str, int]). |
||
| 15 | :param kwargs: Any keyword arguments that are passed through the |
||
| 16 | deserialization process. |
||
| 17 | :return: An object of the first type of the Union that could be |
||
| 18 | deserialized successfully. |
||
| 19 | """ |
||
| 20 | for sub_type in get_union_params(cls): |
||
| 21 | try: |
||
| 22 | return load(obj, sub_type, **kwargs) |
||
| 23 | except JsonsError: |
||
| 24 | pass # Try the next one. |
||
| 25 | else: |
||
| 26 | args_msg = ', '.join([get_class_name(cls_) |
||
| 27 | for cls_ in get_union_params(cls)]) |
||
| 28 | err_msg = ('Could not match the object of type "{}" to any type of ' |
||
| 29 | 'the Union: {}'.format(type(obj).__name__, args_msg)) |
||
| 30 | raise DeserializationError(err_msg, obj, cls) |
||
| 31 |