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

feat: Add support for Literal types. #534

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

arunchaganty
Copy link

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!

@arunchaganty arunchaganty force-pushed the arun-support-literals branch 2 times, most recently from b128a02 to fffd722 Compare June 9, 2024 23:55
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.,

```python
@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`.
```
@mew1033
Copy link

mew1033 commented Sep 9, 2024

Just ran into this issue and saw that it had an open PR. Awesome, thank you! Excited to see it merged.

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

Successfully merging this pull request may close these issues.

2 participants