Skip to content

Commit c20186c

Browse files
authored
gh-93910: [Enum] restore member.member restriction while keeping performance boost (GH-94913)
1 parent 6da988a commit c20186c

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

Lib/enum.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1101,6 +1101,14 @@ def __new__(cls, value):
11011101
def __init__(self, *args, **kwds):
11021102
pass
11031103

1104+
def __getattribute__(self, name):
1105+
self_dict = super().__getattribute__('__dict__')
1106+
cls = super().__getattribute__('__class__')
1107+
value = super().__getattribute__(name)
1108+
if isinstance(value, cls) and name not in self_dict and name in self._member_names_:
1109+
raise AttributeError("<enum '%s'> member has no attribute %r" % (cls.__name__, name))
1110+
return super().__getattribute__(name)
1111+
11041112
def _generate_next_value_(name, start, count, last_values):
11051113
"""
11061114
Generate the next value when not given.

Lib/test/test_enum.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2646,14 +2646,19 @@ class Private(Enum):
26462646
self.assertEqual(Private._Private__corporal, 'Radar')
26472647
self.assertEqual(Private._Private__major_, 'Hoolihan')
26482648

2649-
@unittest.skip("Accessing all values retained for performance reasons, see GH-93910")
26502649
def test_exception_for_member_from_member_access(self):
26512650
with self.assertRaisesRegex(AttributeError, "<enum .Di.> member has no attribute .NO."):
26522651
class Di(Enum):
26532652
YES = 1
26542653
NO = 0
26552654
nope = Di.YES.NO
26562655

2656+
def test_no_exception_for_overridden_member_from_member_access(self):
2657+
class Di(Enum):
2658+
YES = 1
2659+
NO = 0
2660+
Di.YES.NO = Di.NO
2661+
nope = Di.YES.NO
26572662

26582663
def test_dynamic_members_with_static_methods(self):
26592664
#

0 commit comments

Comments
 (0)