lidatong / dataclasses-json

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

feat: Add support for Literal types. #534

Open arunchaganty opened 3 weeks ago

arunchaganty commented 3 weeks ago

This commit extends support of dataclasses_json to dataclasses with fields annotated with Literal types. Literal types allow users to specify a list of valid values, e.g.,

@dataclass
class DataClassWithLiteral(DataClassJsonMixin):
   languages: Literal["C", "C++", "Java"]

When de-serializing data, this commit now validates that the JSON's values are one of those specified in the Literal type.

Change in behavior: Using literal types would previously give users the following warning:

dataclasses_json/mm.py:357: UserWarning: Unknown type C at Foo.langs: typing.Literal['C', 'C++', 'Java']. It's advised to pass the correct marshmallow type to `mm_field`.

Note: this is my first PR to the dataclasses_json library, so I'm not 100% sure what the conventions are. Happy to make any changes requested!