Skip to content

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.

2 participants