[3.13] gh-132684: [Enum] only call _missing_ in __contains__ for Flags (GH-132790) (GH-132896)

gh-132684: [Enum] only call _missing_ in __contains__ for Flags (GH-132790)
(cherry picked from commit 22bc953aa9)

Co-authored-by: Ethan Furman <ethan@stoneleaf.us>
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
This commit is contained in:
Miss Islington (bot) 2025-04-25 22:30:33 +02:00 committed by GitHub
parent 3ff35ba471
commit 08772229c7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 21 additions and 8 deletions

View file

@ -750,14 +750,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

View file

@ -1583,6 +1583,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'