]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.12] gh-131045: [Enum] fix flag containment checks when using values (GH-131053...
authorBénédikt Tran <10796600+picnixz@users.noreply.github.com>
Mon, 24 Mar 2025 09:31:24 +0000 (10:31 +0100)
committerGitHub <noreply@github.com>
Mon, 24 Mar 2025 09:31:24 +0000 (10:31 +0100)
* gh-131045: [Enum] fix flag containment checks when using values (GH-131053)

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: Ethan Furman <ethan@stoneleaf.us>
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 eaa517e2fbc39b76215df0883c7cdc5e04201585..c87aeef715761a3058df6877c41264b2c4912f85 100644 (file)
@@ -771,10 +771,15 @@ 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
-        return value in cls._value2member_map_ or value in cls._unhashable_values_
+        try:
+            cls(value)
+            return True
+        except ValueError:
+            return value in cls._unhashable_values_
 
     def __delattr__(cls, attr):
         # nicer error message when someone tries to delete an attribute
index 2e50ae0fe96586823772e93f458935c8b47363ad..a606002ffe958b17ef147172b079c27834362f53 100644 (file)
@@ -422,6 +422,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'>")
@@ -4848,6 +4849,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`.