예제 #1
0
def _get_parents(cls: type, lizers: list) -> list:
    """
    Return a list of serializers or deserializers that can handle a parent
    of ``cls``.
    :param cls: the type that
    :param lizers: a list of serializers or deserializers.
    :return: a list of serializers or deserializers.
    """
    parents = []
    naked_cls = get_naked_class(cls)
    for cls_ in lizers:
        try:
            if issubclass(naked_cls, cls_):
                parents.append(cls_)
        except (TypeError, AttributeError):
            pass  # Some types do not support `issubclass` (e.g. Union).
    return parents
예제 #2
0
def default_mapping_deserializer(obj: dict, cls: type, **kwargs) -> Mapping:
    """
    Deserialize a (JSON) dict into a mapping by deserializing all items of that
    dict.
    :param obj: the dict that needs deserializing.
    :param cls: the type, optionally with a generic (e.g. Set[str]).
    :param kwargs: any keyword arguments.
    :return: a deserialized set instance.
    """
    cls_ = Mapping
    if hasattr(cls, '__args__'):
        cls_ = MappingType[cls.__args__]
    dict_ = default_dict_deserializer(obj, cls_, **kwargs)
    result = dict_
    # Strip any generics from cls to allow for an instance check.
    naked_cls = get_naked_class(cls)
    if not isinstance(result, naked_cls):
        result = cls(dict_)
    return result
예제 #3
0
def default_iterable_deserializer(obj: list, cls: type, **kwargs) -> Iterable:
    """
    Deserialize a (JSON) list into an ``Iterable`` by deserializing all items
    of that list. The given obj is assumed to be homogeneous; if the list has a
    generic type (e.g. Set[datetime]) then it is assumed that all elements can
    be deserialized to that type.
    :param obj: The list that needs deserializing to an ``Iterable``.
    :param cls: The type, optionally with a generic (e.g. Deque[str]).
    :param kwargs: Any keyword arguments.
    :return: A deserialized ``Iterable`` (e.g. ``set``) instance.
    """
    cls_ = Mapping
    if hasattr(cls, '__args__'):
        cls_ = IterableType[cls.__args__]
    list_ = default_list_deserializer(obj, cls_, **kwargs)
    result = list_
    naked_cls = get_naked_class(cls)
    if not isinstance(result, naked_cls):
        result = naked_cls(list_)
    return result