Skip to content

feat: Add support for Literal types.#534

Open
arunchaganty wants to merge 1 commit into
lidatong:masterfrom
arunchaganty:arun-support-literals
Open

feat: Add support for Literal types.#534
arunchaganty wants to merge 1 commit into
lidatong:masterfrom
arunchaganty:arun-support-literals

Conversation

@arunchaganty

Copy link
Copy Markdown

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`.
```
@arunchaganty arunchaganty force-pushed the arun-support-literals branch from fffd722 to 41e3c26 Compare June 10, 2024 00:02
@mew1033

mew1033 commented Sep 9, 2024

Copy link
Copy Markdown

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