]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-131045: [Enum] fix flag containment checks when using values (GH-131053)
authorEthan Furman <ethan@stoneleaf.us>
Wed, 12 Mar 2025 19:10:47 +0000 (12:10 -0700)
committerGitHub <noreply@github.com>
Wed, 12 Mar 2025 19:10:47 +0000 (12:10 -0700)
Check would fail if value would create a pseudo-member, but that member
had not yet been created.  We now attempt to create a pseudo-member for
a passed-in value first.

Co-authored-by: Tomas R. <tomas.roun8@gmail.com>
Lib/enum.py
Lib/test/test_enum.py
Misc/NEWS.d/next/Library/2025-03-10-12-26-56.gh-issue-131045.s1TssJ.rst [new file with mode: 0644]

index 04443471b40bff2069c25e3b71fcce7de7940a8d..ee963d6a7e67d1d3bb02cd82bbdf587e12981dd0 100644 (file)
@@ -739,12 +739,14 @@ class EnumType(type):
         `value` is in `cls` if:
         1) `value` is a member of `cls`, or
         2) `value` is the value of one of the `cls`'s members.
+        3) `value` is a pseudo-member (flags)
         """
         if isinstance(value, cls):
             return True
         try:
-            return value in cls._value2member_map_
-        except TypeError:
+            cls(value)
+            return True
+        except ValueError:
             return (
                     value in cls._unhashable_values_    # both structures are lists
                     or value in cls._hashable_values_
index 8884295b1ab89cd8d38c23154d1718681fda6c10..1a0026987cd7eb57aa4a087c79ed77695882fd38 100644 (file)
@@ -462,6 +462,7 @@ class _EnumTests:
             self.assertEqual(str(TE), "<flag 'MainEnum'>")
             self.assertEqual(format(TE), "<flag 'MainEnum'>")
             self.assertTrue(TE(5) is self.dupe2)
+            self.assertTrue(7 in TE)
         else:
             self.assertEqual(repr(TE), "<enum 'MainEnum'>")
             self.assertEqual(str(TE), "<enum 'MainEnum'>")
@@ -4954,6 +4955,7 @@ class Color(enum.Enum)
  |      `value` is in `cls` if:
  |      1) `value` is a member of `cls`, or
  |      2) `value` is the value of one of the `cls`'s members.
+ |      3) `value` is a pseudo-member (flags)
  |
  |  __getitem__(name)
  |      Return the member matching `name`.
diff --git a/Misc/NEWS.d/next/Library/2025-03-10-12-26-56.gh-issue-131045.s1TssJ.rst b/Misc/NEWS.d/next/Library/2025-03-10-12-26-56.gh-issue-131045.s1TssJ.rst
new file mode 100644 (file)
index 0000000..b6aa072
--- /dev/null
@@ -0,0 +1 @@
+Fix issue with ``__contains__``, values, and pseudo-members for :class:`enum.Flag`.