Skip to content

Commit 5d2eee5

Browse files
committed
hashable Enum
1 parent ee1ff97 commit 5d2eee5

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

graphene/types/enum.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@ def eq_enum(self, other):
1212
return self.value is other
1313

1414

15+
def hash_enum(self):
16+
return hash(self.name)
17+
18+
1519
EnumType = type(PyEnum)
1620

1721

@@ -22,7 +26,7 @@ class EnumOptions(BaseOptions):
2226

2327
class EnumMeta(SubclassWithMeta_Meta):
2428
def __new__(cls, name_, bases, classdict, **options):
25-
enum_members = dict(classdict, __eq__=eq_enum)
29+
enum_members = dict(classdict, __eq__=eq_enum, __hash__=hash_enum)
2630
# We remove the Meta attribute from the class to not collide
2731
# with the enum values.
2832
enum_members.pop("Meta", None)

graphene/types/tests/test_enum.py

+25
Original file line numberDiff line numberDiff line change
@@ -518,3 +518,28 @@ class Query(ObjectType):
518518
assert result.data == {"createPaint": {"color": "RED"}}
519519

520520
assert color_input_value == RGB.RED
521+
522+
523+
def test_hashable_enum():
524+
class RGB(Enum):
525+
"""Available colors"""
526+
527+
RED = 1
528+
GREEN = 2
529+
BLUE = 3
530+
531+
color_map = {RGB.RED: "a", RGB.BLUE: "b", 1: "c"}
532+
533+
assert color_map[RGB.RED] == "a"
534+
assert color_map[RGB.BLUE] == "b"
535+
assert color_map[1] == "c"
536+
537+
538+
def test_hashable_instance_creation_enum():
539+
Episode = Enum("Episode", [("NEWHOPE", 4), ("EMPIRE", 5), ("JEDI", 6)])
540+
541+
trilogy_map = {Episode.NEWHOPE: "better", Episode.EMPIRE: "best", 5: "foo"}
542+
543+
assert trilogy_map[Episode.NEWHOPE] == "better"
544+
assert trilogy_map[Episode.EMPIRE] == "best"
545+
assert trilogy_map[5] == "foo"

0 commit comments

Comments
 (0)