marshmallow_dataclass icon indicating copy to clipboard operation
marshmallow_dataclass copied to clipboard

Add support for literal enums

Open SquidDev opened this issue 2 years ago • 0 comments

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!

SquidDev avatar Jun 10 '22 10:06 SquidDev