From 8f982ede281073403a2389ba086706ee1bd01ef6 Mon Sep 17 00:00:00 2001 From: Ethan Furman Date: Mon, 21 Apr 2025 21:01:24 -0700 Subject: [PATCH 1/2] only call _missing_ in __contains__ for Flags --- Lib/enum.py | 20 ++++++++++++-------- Lib/test/test_enum.py | 11 +++++++++++ 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/Lib/enum.py b/Lib/enum.py index b5f3ca7ae111d6..ea27c9ef9d2190 100644 --- a/Lib/enum.py +++ b/Lib/enum.py @@ -731,14 +731,18 @@ def __contains__(cls, value): """ if isinstance(value, cls): return True - try: - cls(value) - return True - except ValueError: - return ( - value in cls._unhashable_values_ # both structures are lists - or value in cls._hashable_values_ - ) + if issubclass(cls, Flag): + try: + result = cls._missing_(value) + if isinstance(result, cls): + return True + return False + except ValueError: + pass + return ( + value in cls._unhashable_values_ # both structures are lists + or value in cls._hashable_values_ + ) def __delattr__(cls, attr): # nicer error message when someone tries to delete an attribute diff --git a/Lib/test/test_enum.py b/Lib/test/test_enum.py index dde674164f4a52..68cedc666a59ef 100644 --- a/Lib/test/test_enum.py +++ b/Lib/test/test_enum.py @@ -1569,6 +1569,17 @@ class IntFlag1(IntFlag): self.assertIn(IntEnum1.X, IntFlag1) self.assertIn(IntFlag1.X, IntEnum1) + def test_contains_does_not_call_missing(self): + class AnEnum(Enum): + UNKNOWN = None + LUCKY = 3 + @classmethod + def _missing_(cls, *values): + return cls.UNKNOWN + self.assertTrue(None in AnEnum) + self.assertTrue(3 in AnEnum) + self.assertFalse(7 in AnEnum) + def test_inherited_data_type(self): class HexInt(int): __qualname__ = 'HexInt' From 2122e59cee84c576fdf14dac6cc1cbd914de6b1b Mon Sep 17 00:00:00 2001 From: Ethan Furman Date: Thu, 24 Apr 2025 13:25:59 -0700 Subject: [PATCH 2/2] simplify code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com> --- Lib/enum.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Lib/enum.py b/Lib/enum.py index ea27c9ef9d2190..01fecca3e5aac0 100644 --- a/Lib/enum.py +++ b/Lib/enum.py @@ -734,9 +734,7 @@ def __contains__(cls, value): if issubclass(cls, Flag): try: result = cls._missing_(value) - if isinstance(result, cls): - return True - return False + return isinstance(result, cls) except ValueError: pass return (