mirror of
https://github.com/python/cpython.git
synced 2025-07-07 11:25:30 +00:00
gh-132684: [Enum] only call _missing_ in __contains__ for Flags (GH-132790)
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
This commit is contained in:
parent
63da5cc150
commit
22bc953aa9
2 changed files with 21 additions and 8 deletions
18
Lib/enum.py
18
Lib/enum.py
|
@ -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
|
||||
|
|
|
@ -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'
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue