| Conditions | 4 |
| Total Lines | 22 |
| Code Lines | 11 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
| 1 | from typing import Union |
||
| 8 | def default_union_serializer(obj: object, cls: Union, **kwargs) -> object: |
||
| 9 | """ |
||
| 10 | Serialize an object to any matching type of the given union. The first |
||
| 11 | successful serialization is returned. |
||
| 12 | :param obj: The object that is to be serialized. |
||
| 13 | :param cls: The Union type with a generic (e.g. Union[str, int]). |
||
| 14 | :param kwargs: Any keyword arguments that are passed through the |
||
| 15 | serialization process. |
||
| 16 | :return: An object of the first type of the Union that could be |
||
| 17 | serialized successfully. |
||
| 18 | """ |
||
| 19 | for sub_type in get_union_params(cls): |
||
| 20 | try: |
||
| 21 | return dump(obj, sub_type, **kwargs) |
||
| 22 | except JsonsError: |
||
| 23 | pass # Try the next one. |
||
| 24 | else: |
||
| 25 | args_msg = ', '.join([get_class_name(cls_) |
||
| 26 | for cls_ in get_union_params(cls)]) |
||
| 27 | err_msg = ('Could not match the object of type "{}" to any type of ' |
||
| 28 | 'the Union: {}'.format(str(cls), args_msg)) |
||
| 29 | raise SerializationError(err_msg) |
||
| 30 |