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

Add support for literal enums #200

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

Conversation

SquidDev
Copy link

Consider the following code:

from enum import Enum
from dataclasses import dataclass
from typing import Literal
import marshmallow_dataclass


class Color(Enum):
  RED = 0
  GREEN = 1
  BLUE = 2


@dataclass
class Dc:
  color: Literal[Color.RED]


print(marshmallow_dataclass.class_schema(Dc)().load({"color": "RED"}))

This will currently raise an exception, complaining "RED" is not equal to Color.RED. This is because Literal fields use marshmallow.fields.Raw, which does not reinterpret the string as an enum.

This patch instead interprets the string as an enum if all literal values are of the same enum type, meaning the above code now works.

This is not a more general fix - for instance, Literal[Color.RED, Animal.DOG] will still not work. Fixing this is definitely possible, but would require a more complex solution and I wasn't sure it was worth it. Happy to implement it though if you'd prefer!

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.

1 participant