(original) (raw)
changeset: 85574:1d88d04aade2 user: Ethan Furman ethan@stoneleaf.us date: Fri Sep 06 07:16:48 2013 -0700 files: Lib/enum.py Lib/test/test_enum.py description: Close #18924: Block naive attempts to change an Enum member. diff -r 587bdb940524 -r 1d88d04aade2 Lib/enum.py --- a/Lib/enum.py Fri Sep 06 06:55:58 2013 -0700 +++ b/Lib/enum.py Fri Sep 06 07:16:48 2013 -0700 @@ -263,6 +263,19 @@ def __repr__(cls): return "" % cls.__name__ + def __setattr__(cls, name, value): + """Block attempts to reassign Enum members. + + A simple assignment to the class namespace only changes one of the + several possible ways to get an Enum member from the Enum class, + resulting in an inconsistent Enumeration. + + """ + member_map = cls.__dict__.get('_member_map_', {}) + if name in member_map: + raise AttributeError('Cannot reassign members.') + super().__setattr__(name, value) + def _create_(cls, class_name, names=None, *, module=None, type=None): """Convenience method to create a new Enum class. diff -r 587bdb940524 -r 1d88d04aade2 Lib/test/test_enum.py --- a/Lib/test/test_enum.py Fri Sep 06 06:55:58 2013 -0700 +++ b/Lib/test/test_enum.py Fri Sep 06 07:16:48 2013 -0700 @@ -152,6 +152,11 @@ with self.assertRaises(AttributeError): Season.SPRING.value = 2 + def test_changing_member(self): + Season = self.Season + with self.assertRaises(AttributeError): + Season.WINTER = 'really cold' + def test_invalid_names(self): with self.assertRaises(ValueError): class Wrong(Enum):/ethan@stoneleaf.us