| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
@@ -263,6 +263,19 @@ def __len__(cls): | |||
| 263 | 263 | def __repr__(cls): | |
| 264 | 264 | return "<enum %r>" % cls.__name__ | |
| 265 | 265 | ||
| 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 | + | ||
| 266 | 279 | def _create_(cls, class_name, names=None, *, module=None, type=None): | |
| 267 | 280 | """Convenience method to create a new Enum class. | |
| 268 | 281 | ||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
@@ -152,6 +152,11 @@ def test_value_name(self): | |||
| 152 | 152 | with self.assertRaises(AttributeError): | |
| 153 | 153 | Season.SPRING.value = 2 | |
| 154 | 154 | ||
| 155 | + def test_changing_member(self): | ||
| 156 | + Season = self.Season | ||
| 157 | + with self.assertRaises(AttributeError): | ||
| 158 | + Season.WINTER = 'really cold' | ||
| 159 | + | ||
| 155 | 160 | def test_invalid_names(self): | |
| 156 | 161 | with self.assertRaises(ValueError): | |
| 157 | 162 | class Wrong(Enum): | |
| Back | FazBrowse Home | New Git URL |
0 commit comments