Skip to content

Add support for literal enums #200

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions marshmallow_dataclass/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ class User:
import threading
import types
import warnings
from enum import EnumMeta
from enum import Enum, EnumMeta
from functools import lru_cache, partial
from typing import (
Any,
Expand Down Expand Up @@ -648,7 +648,22 @@ def field_for_schema(

if typing_inspect.is_literal_type(typ):
arguments = typing_inspect.get_args(typ)
return marshmallow.fields.Raw(

field_type = marshmallow.fields.Raw

# If all fields are an enum of the same type, interpret our literal as
# an enum instead.
if (
len(arguments) > 0
and isinstance(arguments[0], Enum)
and all(type(arguments[0]) == type(arg) for arg in arguments)
):
import marshmallow_enum

metadata["enum"] = type(arguments[0])
field_type = marshmallow_enum.EnumField

return field_type(
validate=(
marshmallow.validate.Equal(arguments[0])
if len(arguments) == 1
Expand Down
21 changes: 16 additions & 5 deletions tests/test_field_for_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@
)


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


class TestFieldForSchema(unittest.TestCase):
def assertFieldsEqual(self, a: fields.Field, b: fields.Field):
self.assertEqual(a.__class__, b.__class__, "field class")
Expand Down Expand Up @@ -90,11 +96,6 @@ def test_optional_str(self):
def test_enum(self):
import marshmallow_enum

class Color(Enum):
RED: 1
GREEN: 2
BLUE: 3

self.assertFieldsEqual(
field_for_schema(Color),
marshmallow_enum.EnumField(enum=Color, required=True),
Expand All @@ -112,6 +113,16 @@ def test_literal_multiple_types(self):
fields.Raw(required=True, validate=validate.OneOf(("a", 1, 1.23, True))),
)

def test_literal_enum(self):
import marshmallow_enum

self.assertFieldsEqual(
field_for_schema(Literal[Color.BLUE]),
marshmallow_enum.EnumField(
required=True, enum=Color, validate=validate.Equal(Color.BLUE)
),
)

def test_final(self):
self.assertFieldsEqual(
field_for_schema(Final[str]), fields.String(required=True)
Expand Down