Skip to content

Commit 12de5c7

Browse files
committed
Enums created with functional syntax are now iterable. Close pylint-dev/pylint#992
1 parent 36cfe68 commit 12de5c7

File tree

3 files changed

+25
-0
lines changed

3 files changed

+25
-0
lines changed

ChangeLog

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ Change log for the astroid package (used to be astng)
44
--
55
* Enums created with functional syntax are now iterable
66

7+
* Enums created with functional syntax are now subscriptable
8+
79
* Don't crash when getting the string representation of BadUnaryOperationMessage
810

911
In some cases, when the operand does not have a .name attribute,

astroid/brain/brain_namedtuple_enum.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,16 @@ class EnumAttribute(object):
200200
return [EnumAttribute()]
201201
def __next__(self):
202202
return next(iter(self))
203+
def __getitem__(self, attr):
204+
class Value(object):
205+
@property
206+
def name(self):
207+
return ''
208+
@property
209+
def value(self):
210+
return attr
211+
212+
return Value()
203213
''')
204214
class_node = infer_func_form(node, enum_meta,
205215
context=context, enum=True)[0]

astroid/tests/unittest_brain.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -584,6 +584,19 @@ def test_enum_func_form_iterable(self):
584584
self.assertIsInstance(inferred, astroid.Instance)
585585
self.assertTrue(inferred.getattr('__iter__'))
586586

587+
def test_enum_func_form_subscriptable(self):
588+
instance, name = builder.extract_node('''
589+
from enum import Enum
590+
Animal = Enum('Animal', 'ant bee cat dog')
591+
Animal['ant'] #@
592+
Animal['ant'].name #@
593+
''')
594+
instance = next(instance.infer())
595+
self.assertIsInstance(instance, astroid.Instance)
596+
597+
inferred = next(name.infer())
598+
self.assertIsInstance(inferred, astroid.Const)
599+
587600

588601
@unittest.skipUnless(HAS_DATEUTIL, "This test requires the dateutil library.")
589602
class DateutilBrainTest(unittest.TestCase):

0 commit comments

Comments
 (0)