Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 10 additions & 8 deletions Lib/enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -750,14 +750,16 @@ def __contains__(cls, value):
"""
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
Expand Down
11 changes: 11 additions & 0 deletions Lib/test/test_enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -1583,6 +1583,17 @@ class IntFlag1(IntFlag):
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'
Expand Down
Loading