Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inconsistent checks for invalid value type for str field type #42

Open
OliverColeman opened this issue Feb 24, 2021 · 3 comments
Open
Labels
enhancement New feature or request

Comments

@OliverColeman
Copy link

If a class based on DataClassDictMixin has a field with type str it will construct instances from data that contains data of other types for that field, including numbers, lists, and dicts. However fields of other types, eg int, do not accept other non-compatible types. Not sure if this is intentional and I'm missing something here, but it kinda seems like unexpected/undesirable behaviour when you want the input data to be validated.

The following example only throws an error on the very last line:

from dataclasses import dataclass
from mashumaro import DataClassDictMixin


@dataclass
class StrType(DataClassDictMixin):
    a: str

StrType.from_dict({'a': 1})
StrType.from_dict({'a': [1, 2]})
StrType.from_dict({'a': {'b': 1}})


@dataclass
class IntType(DataClassDictMixin):
    a: int

IntType.from_dict({'a': 'blah'})
@OliverColeman OliverColeman changed the title Inconsistent checks for invalid value type for str type Inconsistent checks for invalid value type for str field type Feb 24, 2021
@Fatal1ty
Copy link
Owner

There is no strict validation at the moment for the sake of performance. It's not needed in many cases but I'm going to add optional validation. It will be turned on in the field or config options.

@Fatal1ty
Copy link
Owner

Current workaround is to use explicit serialization strategy either in the config or at the field:

def coerce_str(value):
    return str(value)


def validate_str(value):
    if not isinstance(value, str):
        raise ValueError
    return value


@dataclass
class StrType(DataClassDictMixin):
    a: str
    # a: str = field(metadata={"deserialize": validate_str})

    class Config:
        serialization_strategy = {
            str: {
                "deserialize": validate_str,
                # "deserialize": coerce_str,
            },
        }

@Fatal1ty Fatal1ty added the enhancement New feature or request label Mar 26, 2023
@Tinche

This comment was marked as off-topic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

3 participants