Skip to content

feat: add ability to provide a type name to enum when using from_enum #1430

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

Merged
Merged
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
7 changes: 5 additions & 2 deletions graphene/types/enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,18 @@ def __call__(cls, *args, **kwargs): # noqa: N805
return super(EnumMeta, cls).__call__(*args, **kwargs)
# return cls._meta.enum(*args, **kwargs)

def from_enum(cls, enum, description=None, deprecation_reason=None): # noqa: N805
def from_enum(
cls, enum, name=None, description=None, deprecation_reason=None
): # noqa: N805
name = name or enum.__name__
description = description or enum.__doc__
meta_dict = {
"enum": enum,
"description": description,
"deprecation_reason": deprecation_reason,
}
meta_class = type("Meta", (object,), meta_dict)
return type(meta_class.enum.__name__, (Enum,), {"Meta": meta_class})
return type(name, (Enum,), {"Meta": meta_class})


class Enum(UnmountedType, BaseType, metaclass=EnumMeta):
Expand Down
46 changes: 46 additions & 0 deletions graphene/types/tests/test_enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,52 @@ def resolve_color_by_name(_, info):
assert results.data["colorByName"] == Color.RED.name


def test_enum_with_name():
from enum import Enum as PyEnum

class Color(PyEnum):
RED = 1
YELLOW = 2
BLUE = 3

GColor = Enum.from_enum(Color, description="original colors")
UniqueGColor = Enum.from_enum(
Color, name="UniqueColor", description="unique colors"
)

class Query(ObjectType):
color = GColor(required=True)
unique_color = UniqueGColor(required=True)

schema = Schema(query=Query)

assert (
str(schema).strip()
== dedent(
'''
type Query {
color: Color!
uniqueColor: UniqueColor!
}

"""original colors"""
enum Color {
RED
YELLOW
BLUE
}

"""unique colors"""
enum UniqueColor {
RED
YELLOW
BLUE
}
'''
).strip()
)


def test_enum_resolver_invalid():
from enum import Enum as PyEnum

Expand Down