How to use the mashumaro.exceptions.UnserializableDataError function in mashumaro

To help you get started, we’ve selected a few mashumaro examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Fatal1ty / mashumaro / tests / test_data_types.py View on Github external
def test_unsupported_typing_primitives(x_type):
    with pytest.raises(UnserializableDataError):
        @dataclass
        class _(DataClassDictMixin):
            x: x_type
github Fatal1ty / mashumaro / mashumaro / exceptions.py View on Github external
return type_name(self.field_type)

    @property
    def holder_class_name(self):
        return type_name(self.holder_class)

    def __str__(self):
        return f'Field "{self.field_name}" of type {self.field_type_name}' \
               f' is missing in {self.holder_class_name} instance'


class UnserializableDataError(TypeError):
    pass


class UnserializableField(UnserializableDataError):
    def __init__(self, field_name, field_type, holder_class, msg=None):
        self.field_name = field_name
        self.field_type = field_type
        self.holder_class = holder_class
        self.msg = msg

    @property
    def field_type_name(self):
        return type_name(self.field_type)

    @property
    def holder_class_name(self):
        return type_name(self.holder_class)

    def __str__(self):
        s = f'Field "{self.field_name}" of type {self.field_type_name} ' \
github Fatal1ty / mashumaro / mashumaro / serializer / base / metaprogramming.py View on Github external
raise UnserializableDataError(
                            'ChainMaps with dataclasses as keys '
                            'are not supported by mashumaro')
                    else:
                        return f'[{{{inner_expr(0,"key")}:{inner_expr(1)} ' \
                               f'for key,value in m.items()}} ' \
                               f'for m in value.maps]'
            elif issubclass(origin_type, typing.Mapping):
                if ftype is dict:
                    raise UnserializableField(
                        fname, ftype, parent,
                        'Use typing.Dict[KT,VT] or Mapping[KT,VT] instead'
                    )
                elif is_generic(ftype):
                    if is_dataclass(args[0]):
                        raise UnserializableDataError(
                            'Mappings with dataclasses as keys '
                            'are not supported by mashumaro')
                    else:
                        return f'{{{inner_expr(0,"key")}: {inner_expr(1)} ' \
                               f'for key, value in {value_name}.items()}}'
            elif issubclass(origin_type, typing.ByteString):
                return f'{value_name} if use_bytes else ' \
                       f'encodebytes({value_name}).decode()'
            elif issubclass(origin_type, str):
                return value_name
            elif issubclass(origin_type, typing.Sequence):
                if is_generic(ftype):
                    return f'[{inner_expr()} for value in {value_name}]'
        elif issubclass(origin_type, os.PathLike):
            return f'{value_name}.__fspath__()'
        elif issubclass(origin_type, enum.Enum):
github Fatal1ty / mashumaro / mashumaro / serializer / base / metaprogramming.py View on Github external
origin_type = get_type_origin(ftype)
        if is_special_typing_primitive(origin_type):
            if origin_type is typing.Any:
                return value_name
            elif is_union(ftype):
                args = getattr(ftype, '__args__', ())
                if len(args) == 2 and args[1] == NoneType:  # it is Optional
                    return self._pack_value(fname, args[0], parent)
                else:
                    raise UnserializableDataError(
                        'Unions are not supported by mashumaro')
            elif origin_type is typing.AnyStr:
                raise UnserializableDataError(
                    'AnyStr is not supported by mashumaro')
            elif is_type_var(ftype):
                raise UnserializableDataError(
                    'TypeVars are not supported by mashumaro')
            else:
                raise UnserializableDataError(
                    f'{ftype} as a field type is not supported by mashumaro')
        elif issubclass(origin_type, typing.Collection):
            args = getattr(ftype, '__args__', ())

            def inner_expr(arg_num=0, v_name='value'):
                return self._pack_value(fname, args[arg_num], parent, v_name)

            if issubclass(origin_type, (typing.List,
                                        typing.Deque,
                                        typing.Tuple,
                                        typing.AbstractSet)):
                if is_generic(ftype):
                    return f'[{inner_expr()} for value in {value_name}]'
github Fatal1ty / mashumaro / mashumaro / serializer / base / metaprogramming.py View on Github external
return value_name
            elif is_union(ftype):
                args = getattr(ftype, '__args__', ())
                if len(args) == 2 and args[1] == NoneType:  # it is Optional
                    return self._pack_value(fname, args[0], parent)
                else:
                    raise UnserializableDataError(
                        'Unions are not supported by mashumaro')
            elif origin_type is typing.AnyStr:
                raise UnserializableDataError(
                    'AnyStr is not supported by mashumaro')
            elif is_type_var(ftype):
                raise UnserializableDataError(
                    'TypeVars are not supported by mashumaro')
            else:
                raise UnserializableDataError(
                    f'{ftype} as a field type is not supported by mashumaro')
        elif issubclass(origin_type, typing.Collection):
            args = getattr(ftype, '__args__', ())

            def inner_expr(arg_num=0, v_name='value'):
                return self._pack_value(fname, args[arg_num], parent, v_name)

            if issubclass(origin_type, (typing.List,
                                        typing.Deque,
                                        typing.Tuple,
                                        typing.AbstractSet)):
                if is_generic(ftype):
                    return f'[{inner_expr()} for value in {value_name}]'
                elif ftype is list:
                    raise UnserializableField(
                        fname, ftype, parent, 'Use typing.List[T] instead')
github Fatal1ty / mashumaro / mashumaro / serializer / base / metaprogramming.py View on Github external
fname, ftype, parent, 'Use typing.FrozenSet[T] instead')
            elif issubclass(origin_type, typing.AbstractSet):
                if is_generic(ftype):
                    return f'set([{inner_expr()} for value in {value_name}])'
                elif ftype is set:
                    raise UnserializableField(
                        fname, ftype, parent, 'Use typing.Set[T] instead')
            elif issubclass(origin_type, typing.ChainMap):
                if ftype is collections.ChainMap:
                    raise UnserializableField(
                        fname, ftype, parent,
                        'Use typing.ChainMap[KT,VT] instead'
                    )
                elif is_generic(ftype):
                    if is_dataclass(args[0]):
                        raise UnserializableDataError(
                            'ChainMaps with dataclasses as keys '
                            'are not supported by mashumaro')
                    else:
                        return f'collections.ChainMap(' \
                               f'*[{{{inner_expr(0,"key")}:{inner_expr(1)} ' \
                               f'for key, value in m.items()}} ' \
                               f'for m in {value_name}])'
            elif issubclass(origin_type, typing.Mapping):
                if ftype is dict:
                    raise UnserializableField(
                        fname, ftype, parent,
                        'Use typing.Dict[KT,VT] or Mapping[KT,VT] instead'
                    )
                elif is_generic(ftype):
                    if is_dataclass(args[0]):
                        raise UnserializableDataError(
github Fatal1ty / mashumaro / mashumaro / serializer / base / metaprogramming.py View on Github external
fname, ftype, parent, 'Use typing.Tuple[T] instead')
                elif ftype is set:
                    raise UnserializableField(
                        fname, ftype, parent, 'Use typing.Set[T] instead')
                elif ftype is frozenset:
                    raise UnserializableField(
                        fname, ftype, parent, 'Use typing.FrozenSet[T] instead')
            elif issubclass(origin_type, typing.ChainMap):
                if ftype is collections.ChainMap:
                    raise UnserializableField(
                        fname, ftype, parent,
                        'Use typing.ChainMap[KT,VT] instead'
                    )
                elif is_generic(ftype):
                    if is_dataclass(args[0]):
                        raise UnserializableDataError(
                            'ChainMaps with dataclasses as keys '
                            'are not supported by mashumaro')
                    else:
                        return f'[{{{inner_expr(0,"key")}:{inner_expr(1)} ' \
                               f'for key,value in m.items()}} ' \
                               f'for m in value.maps]'
            elif issubclass(origin_type, typing.Mapping):
                if ftype is dict:
                    raise UnserializableField(
                        fname, ftype, parent,
                        'Use typing.Dict[KT,VT] or Mapping[KT,VT] instead'
                    )
                elif is_generic(ftype):
                    if is_dataclass(args[0]):
                        raise UnserializableDataError(
                            'Mappings with dataclasses as keys '
github Fatal1ty / mashumaro / mashumaro / serializer / base / metaprogramming.py View on Github external
'ChainMaps with dataclasses as keys '
                            'are not supported by mashumaro')
                    else:
                        return f'collections.ChainMap(' \
                               f'*[{{{inner_expr(0,"key")}:{inner_expr(1)} ' \
                               f'for key, value in m.items()}} ' \
                               f'for m in {value_name}])'
            elif issubclass(origin_type, typing.Mapping):
                if ftype is dict:
                    raise UnserializableField(
                        fname, ftype, parent,
                        'Use typing.Dict[KT,VT] or Mapping[KT,VT] instead'
                    )
                elif is_generic(ftype):
                    if is_dataclass(args[0]):
                        raise UnserializableDataError(
                            'Mappings with dataclasses as keys '
                            'are not supported by mashumaro')
                    else:
                        return f'{{{inner_expr(0,"key")}: {inner_expr(1)} ' \
                               f'for key, value in {value_name}.items()}}'
            elif issubclass(origin_type, typing.ByteString):
                if origin_type is bytes:
                    return f'{value_name} if use_bytes else ' \
                           f'decodebytes({value_name}.encode())'
                elif origin_type is bytearray:
                    return f'bytearray({value_name} if use_bytes else ' \
                           f'decodebytes({value_name}.encode()))'
            elif issubclass(origin_type, str):
                return value_name
            elif issubclass(origin_type, typing.Sequence):
                if is_generic(ftype):
github Fatal1ty / mashumaro / mashumaro / serializer / base / metaprogramming.py View on Github external
return value_name
            elif is_union(ftype):
                args = getattr(ftype, '__args__', ())
                if len(args) == 2 and args[1] == NoneType:  # it is Optional
                    return self._unpack_field_value(fname, args[0], parent)
                else:
                    raise UnserializableDataError(
                        'Unions are not supported by mashumaro')
            elif origin_type is typing.AnyStr:
                raise UnserializableDataError(
                    'AnyStr is not supported by mashumaro')
            elif is_type_var(ftype):
                raise UnserializableDataError(
                    'TypeVars are not supported by mashumaro')
            else:
                raise UnserializableDataError(
                    f'{ftype} as a field type is not supported by mashumaro')
        elif issubclass(origin_type, typing.Collection):
            args = getattr(ftype, '__args__', ())

            def inner_expr(arg_num=0, v_name='value'):
                return self._unpack_field_value(
                    fname, args[arg_num], parent, v_name)

            if issubclass(origin_type, typing.List):
                if is_generic(ftype):
                    return f'[{inner_expr()} for value in {value_name}]'
                elif ftype is list:
                    raise UnserializableField(
                        fname, ftype, parent, 'Use typing.List[T] instead')
            elif issubclass(origin_type, typing.Deque):
                if is_generic(ftype):
github Fatal1ty / mashumaro / mashumaro / serializer / base / metaprogramming.py View on Github external
if issubclass(ftype, SerializableType):
                return f'{value_name}._serialize()'
        if isinstance(ftype, SerializationStrategy):
            return f"self.__dataclass_fields__['{fname}'].type" \
                f"._serialize({value_name})"

        origin_type = get_type_origin(ftype)
        if is_special_typing_primitive(origin_type):
            if origin_type is typing.Any:
                return value_name
            elif is_union(ftype):
                args = getattr(ftype, '__args__', ())
                if len(args) == 2 and args[1] == NoneType:  # it is Optional
                    return self._pack_value(fname, args[0], parent)
                else:
                    raise UnserializableDataError(
                        'Unions are not supported by mashumaro')
            elif origin_type is typing.AnyStr:
                raise UnserializableDataError(
                    'AnyStr is not supported by mashumaro')
            elif is_type_var(ftype):
                raise UnserializableDataError(
                    'TypeVars are not supported by mashumaro')
            else:
                raise UnserializableDataError(
                    f'{ftype} as a field type is not supported by mashumaro')
        elif issubclass(origin_type, typing.Collection):
            args = getattr(ftype, '__args__', ())

            def inner_expr(arg_num=0, v_name='value'):
                return self._pack_value(fname, args[arg_num], parent, v_name)