[3.12] gh-131045: [Enum] fix flag containment checks when using values (GH-131053) (#131232)

* 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>
This commit is contained in:
Bénédikt Tran 2025-03-24 10:31:24 +01:00 committed by GitHub
parent 7f2de07808
commit 8a9aee7126
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 9 additions and 1 deletions

View 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

View 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`.

View file

@ -0,0 +1 @@
Fix issue with ``__contains__``, values, and pseudo-members for :class:`enum.Flag`.