Skip to content

Commit

Permalink
Fix inference of Enum.__members__ property for subclasses
Browse files Browse the repository at this point in the history
Ref pylint-dev/pylint#2626. Ref pylint-dev/pylint#3535. Ref pylint-dev/pylint#4358.
This updates the namedtuple/enum brain to add a dictionary for
__members__
  • Loading branch information
nelfin committed May 13, 2021
1 parent 8030d6a commit 53e9c62
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
10 changes: 10 additions & 0 deletions astroid/brain/brain_namedtuple_enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,7 @@ def infer_enum_class(node):
if node.root().name == "enum":
# Skip if the class is directly from enum module.
break
dunder_members = {}
for local, values in node.locals.items():
if any(not isinstance(value, nodes.AssignName) for value in values):
continue
Expand Down Expand Up @@ -372,7 +373,16 @@ def name(self):
for method in node.mymethods():
fake.locals[method.name] = [method]
new_targets.append(fake.instantiate_class())
dunder_members[local] = fake
node.locals[local] = new_targets
members = nodes.Dict(parent=node)
members.postinit(
[
(nodes.Const(k, parent=members), nodes.Name(v.name, parent=members))
for k, v in dunder_members.items()
]
)
node.locals["__members__"] = [members]
break
return node

Expand Down
16 changes: 16 additions & 0 deletions tests/unittest_scoped_nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2054,6 +2054,22 @@ class Derived(Parent):
assert isinstance(inferred, objects.Property)


def test_issue940_enums_as_a_real_world_usecase():
node = builder.extract_node(
"""
from enum import Enum
class Sounds(Enum):
bee = "buzz"
cat = "meow"
Sounds.__members__
"""
)
inferred_result = next(node.infer())
assert isinstance(inferred_result, nodes.Dict)
actual = [k.value for k, _ in inferred_result.items]
assert sorted(actual) == ["bee", "cat"]


def test_metaclass_cannot_infer_call_yields_an_instance():
node = builder.extract_node(
"""
Expand Down

0 comments on commit 53e9c62

Please sign in to comment.