FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Close #18924: Block naive attempts to change an Enum member. · python/cpython@f203f2d · GitHub

Repository navigation

Commit f203f2d

Browse files
committed
Close #18924: Block naive attempts to change an Enum member.
1 parent 96d848a commit f203f2d

2 files changed

Lines changed: 18 additions & 0 deletions

File tree

‎Lib/enum.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,19 @@ def __len__(cls):
263263
def __repr__(cls):
264264
return "<enum %r>" % cls.__name__
265265

266+
def __setattr__(cls, name, value):
267+
"""Block attempts to reassign Enum members.
268+
269+
A simple assignment to the class namespace only changes one of the
270+
several possible ways to get an Enum member from the Enum class,
271+
resulting in an inconsistent Enumeration.
272+
273+
"""
274+
member_map = cls.__dict__.get('_member_map_', {})
275+
if name in member_map:
276+
raise AttributeError('Cannot reassign members.')
277+
super().__setattr__(name, value)
278+
266279
def _create_(cls, class_name, names=None, *, module=None, type=None):
267280
"""Convenience method to create a new Enum class.
268281

‎Lib/test/test_enum.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,11 @@ def test_value_name(self):
152152
with self.assertRaises(AttributeError):
153153
Season.SPRING.value = 2
154154

155+
def test_changing_member(self):
156+
Season = self.Season
157+
with self.assertRaises(AttributeError):
158+
Season.WINTER = 'really cold'
159+
155160
def test_invalid_names(self):
156161
with self.assertRaises(ValueError):
157162
class Wrong(Enum):

0 commit comments

Comments
 (0)

Back | FazBrowse Home | New Git URL