Skip to content

Commit 8b914d2

Browse files
bdbarabanmiss-islington
authored andcommitted
bpo-35899: Fix Enum handling of empty and weird strings (GH-11891)
Co-authored-by: Maxwell <[email protected]> Co-authored-by: Stéphane Wirtel <[email protected]> https://bugs.python.org/issue35899
1 parent 8b50400 commit 8b914d2

File tree

3 files changed

+27
-8
lines changed

3 files changed

+27
-8
lines changed

Lib/enum.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,18 +19,19 @@ def _is_descriptor(obj):
1919

2020
def _is_dunder(name):
2121
"""Returns True if a __dunder__ name, False otherwise."""
22-
return (name[:2] == name[-2:] == '__' and
23-
name[2:3] != '_' and
24-
name[-3:-2] != '_' and
25-
len(name) > 4)
22+
return (len(name) > 4 and
23+
name[:2] == name[-2:] == '__' and
24+
name[2] != '_' and
25+
name[-3] != '_')
2626

2727

2828
def _is_sunder(name):
2929
"""Returns True if a _sunder_ name, False otherwise."""
30-
return (name[0] == name[-1] == '_' and
30+
return (len(name) > 2 and
31+
name[0] == name[-1] == '_' and
3132
name[1:2] != '_' and
32-
name[-2:-1] != '_' and
33-
len(name) > 2)
33+
name[-2:-1] != '_')
34+
3435

3536
def _make_class_unpicklable(cls):
3637
"""Make the given class un-picklable."""
@@ -150,7 +151,7 @@ def __new__(metacls, cls, bases, classdict):
150151
_order_ = classdict.pop('_order_', None)
151152

152153
# check for illegal enum names (any others?)
153-
invalid_names = set(enum_members) & {'mro', }
154+
invalid_names = set(enum_members) & {'mro', ''}
154155
if invalid_names:
155156
raise ValueError('Invalid enum member name: {0}'.format(
156157
','.join(invalid_names)))

Lib/test/test_enum.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2730,6 +2730,23 @@ def cycle_enum():
27302730
self.assertEqual(256, len(seen), 'too many composite members created')
27312731

27322732

2733+
class TestEmptyAndNonLatinStrings(unittest.TestCase):
2734+
2735+
def test_empty_string(self):
2736+
with self.assertRaises(ValueError):
2737+
empty_abc = Enum('empty_abc', ('', 'B', 'C'))
2738+
2739+
def test_non_latin_character_string(self):
2740+
greek_abc = Enum('greek_abc', ('\u03B1', 'B', 'C'))
2741+
item = getattr(greek_abc, '\u03B1')
2742+
self.assertEqual(item.value, 1)
2743+
2744+
def test_non_latin_number_string(self):
2745+
hebrew_123 = Enum('hebrew_123', ('\u05D0', '2', '3'))
2746+
item = getattr(hebrew_123, '\u05D0')
2747+
self.assertEqual(item.value, 1)
2748+
2749+
27332750
class TestUnique(unittest.TestCase):
27342751

27352752
def test_unique_clean(self):
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Enum has been fixed to correctly handle empty strings and strings with non-Latin characters (ie. 'α', 'א') without crashing. Original patch contributed by Maxwell. Assisted by Stéphane Wirtel.

0 commit comments

Comments
 (0)