示例#1
0
def default_tuple_deserializer(obj: list,
                               cls: type = None,
                               *,
                               key_transformer: Optional[Callable[[str],
                                                                  str]] = None,
                               **kwargs) -> object:
    """
    Deserialize a (JSON) list into a tuple by deserializing all items of that
    list.
    :param obj: the tuple that needs deserializing.
    :param cls: the type optionally with a generic (e.g. Tuple[str, int]).
    :param kwargs: any keyword arguments.
    :return: a deserialized tuple instance.
    """
    if hasattr(cls, '_fields'):
        return default_namedtuple_deserializer(obj,
                                               cls,
                                               key_transformer=key_transformer,
                                               **kwargs)
    cls_args = get_args(cls)
    if cls_args:
        tuple_types = getattr(cls, '__tuple_params__', cls_args)
        if tuple_with_ellipsis(cls):
            tuple_types = [tuple_types[0]] * len(obj)
        list_ = [
            load(value, tuple_types[i], **kwargs)
            for i, value in enumerate(obj)
        ]
    else:
        list_ = [load(value, **kwargs) for i, value in enumerate(obj)]
    return tuple(list_)
示例#2
0
def default_tuple_serializer(obj: tuple,
                             cls: Optional[type] = None,
                             **kwargs) -> Union[list, dict]:
    """
    Serialize the given ``obj`` to a list of serialized objects.
    :param obj: the tuple that is to be serialized.
    :param cls: the type of the ``obj``.
    :param kwargs: any keyword arguments that may be given to the serialization
    process.
    :return: a list of which all elements are serialized.
    """
    if hasattr(obj, '_fields'):
        return default_namedtuple_serializer(obj, **kwargs)

    cls_ = cls
    if cls and tuple_with_ellipsis(cls):
        cls_ = Tuple[(get_args(cls)[0], ) * len(obj)]

    return default_iterable_serializer(obj, cls_, **kwargs)