]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-132684: [Enum] only call _missing_ in __contains__ for Flags (GH-132790)
authorEthan Furman <ethan@stoneleaf.us>
Fri, 25 Apr 2025 06:13:54 +0000 (23:13 -0700)
committerGitHub <noreply@github.com>
Fri, 25 Apr 2025 06:13:54 +0000 (23:13 -0700)
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
Lib/enum.py
Lib/test/test_enum.py

index b5f3ca7ae111d6266e2d7ad2ce714d4844b4dc7a..01fecca3e5aac02190244f94307286dfb760269e 100644 (file)
@@ -731,14 +731,16 @@ class EnumType(type):
         """
         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)
+                return isinstance(result, cls)
+            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
index dde674164f4a520983292a73d72ff4df4a61aba2..68cedc666a59ef051c4d0bb1aa8290f60490e998 100644 (file)
@@ -1569,6 +1569,17 @@ class TestSpecial(unittest.TestCase):
         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'