lidatong / dataclasses-json

Easily serialize Data Classes to and from JSON
MIT License
1.34k stars 150 forks source link

[FEATURE] Raise ValidationError if JSON doesn't match any of the types in Union #522

Open PatrickF1 opened 4 months ago

PatrickF1 commented 4 months ago

Description

The current behavior of decoding Union types with from_dict is if none of the types in the Union matches, then the field becomes a dict. To me, I would have expected it to raise ValidationError, and the dict is a surprise to the users of the field

Possible solution

Raise ValidationError if nothing in the Union matches.

Alternatives

For now, I have added to the object

def __post_init__(self) -> None:
    if isinstance(self.params, dict):
        raise Exception("params is missing some fields")

Context

No response