Server : LiteSpeed System : Linux in-mum-web1112.main-hosting.eu 4.18.0-553.34.1.lve.el8.x86_64 #1 SMP Thu Jan 9 16:30:32 UTC 2025 x86_64 User : u451330669 ( 451330669) PHP Version : 8.2.27 Disable Function : NONE Directory : /opt/alt/python311/lib/python3.11/site-packages/jsons/deserializers/ |
from typing import Union
from jsons._common_impl import get_class_name
from jsons._compatibility_impl import get_union_params
from jsons._load_impl import load
from jsons.exceptions import JsonsError, DeserializationError
def default_union_deserializer(obj: object, cls: Union, **kwargs) -> object:
"""
Deserialize an object to any matching type of the given union. The first
successful deserialization is returned.
:param obj: The object that needs deserializing.
:param cls: The Union type with a generic (e.g. Union[str, int]).
:param kwargs: Any keyword arguments that are passed through the
deserialization process.
:return: An object of the first type of the Union that could be
deserialized successfully.
"""
for sub_type in get_union_params(cls):
try:
return load(obj, sub_type, **kwargs)
except JsonsError:
pass # Try the next one.
else:
args_msg = ', '.join([get_class_name(cls_)
for cls_ in get_union_params(cls)])
err_msg = ('Could not match the object of type "{}" to any type of '
'the Union: {}'.format(type(obj).__name__, args_msg))
raise DeserializationError(err_msg, obj, cls)