From e70c26af6d5ad2bc8f41e9ca892cd5e88f044e1e Mon Sep 17 00:00:00 2001 From: Kevin Le Date: Thu, 29 Sep 2022 16:41:42 -0700 Subject: [PATCH] hashable Enum --- graphene/types/enum.py | 6 +++++- graphene/types/tests/test_enum.py | 15 +++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/graphene/types/enum.py b/graphene/types/enum.py index e5cc50ed2..0f68236b4 100644 --- a/graphene/types/enum.py +++ b/graphene/types/enum.py @@ -12,6 +12,10 @@ def eq_enum(self, other): return self.value is other +def hash_enum(self): + return hash(self.name) + + EnumType = type(PyEnum) @@ -22,7 +26,7 @@ class EnumOptions(BaseOptions): class EnumMeta(SubclassWithMeta_Meta): def __new__(cls, name_, bases, classdict, **options): - enum_members = dict(classdict, __eq__=eq_enum) + enum_members = dict(classdict, __eq__=eq_enum, __hash__=hash_enum) # We remove the Meta attribute from the class to not collide # with the enum values. enum_members.pop("Meta", None) diff --git a/graphene/types/tests/test_enum.py b/graphene/types/tests/test_enum.py index 679de16e4..a0a077d63 100644 --- a/graphene/types/tests/test_enum.py +++ b/graphene/types/tests/test_enum.py @@ -518,3 +518,18 @@ class Query(ObjectType): assert result.data == {"createPaint": {"color": "RED"}} assert color_input_value == RGB.RED + + +def test_hashable_enum(): + class RGB(Enum): + """Available colors""" + + RED = 1 + GREEN = 2 + BLUE = 3 + + color_map = {RGB.RED: "a", RGB.BLUE: "b", 1: "c"} + + assert color_map[RGB.RED] == "a" + assert color_map[RGB.BLUE] == "b" + assert color_map[1] == "c"