Skip to content

Fixed being unable to access class attributes on a NamedTuple #673

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 20, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions ChangeLog
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ Release Date: TBA

Close #665

* Fix being unable to access class attributes on a NamedTuple.

Close PyCQA/pylint#1628


What's New in astroid 2.2.0?
============================
Expand Down
9 changes: 9 additions & 0 deletions astroid/brain/brain_namedtuple_enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,15 @@ def infer_typing_namedtuple_class(class_node, context=None):
generated_class_node = next(infer_named_tuple(node, context))
for method in class_node.mymethods():
generated_class_node.locals[method.name] = [method]

for assign in class_node.body:
if not isinstance(assign, nodes.Assign):
continue

for target in assign.targets:
attr = target.name
generated_class_node.locals[attr] = class_node.locals[attr]

return iter((generated_class_node,))


Expand Down
6 changes: 6 additions & 0 deletions astroid/tests/unittest_brain.py
Original file line number Diff line number Diff line change
Expand Up @@ -1006,6 +1006,7 @@ def test_namedtuple_class_form(self):
from typing import NamedTuple

class Example(NamedTuple):
CLASS_ATTR = "class_attr"
mything: int

Example(mything=1)
Expand All @@ -1014,6 +1015,11 @@ class Example(NamedTuple):
inferred = next(result.infer())
self.assertIsInstance(inferred, astroid.Instance)

class_attr = inferred.getattr("CLASS_ATTR")[0]
self.assertIsInstance(class_attr, astroid.AssignName)
const = next(class_attr.infer())
self.assertEqual(const.value, "class_attr")

def test_typing_types(self):
ast_nodes = builder.extract_node(
"""
Expand Down