-
-
Notifications
You must be signed in to change notification settings - Fork 45
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
Comments
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. |
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,
},
} |
This comment was marked as off-topic.
This comment was marked as off-topic.
Now the input values will be converted to a string if we are expected to get a string so that there are no surprises at runtime. I think this is reasonable default behavior in the absence of strict validation. If someone needs to validate that an input value is a string, then this can be done in different ways. assert StrType.from_dict({'a': 1}) == StrType("1")
assert StrType.from_dict({'a': [1, 2]}) == StrType("[1, 2]")
assert StrType.from_dict({'a': {'b': 1}}) == StrType("{'b': 1}") |
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:
The text was updated successfully, but these errors were encountered: