Skip to content

Commit

Permalink
Fix crash when evaluating typing.NamedTuple (#956)
Browse files Browse the repository at this point in the history
  • Loading branch information
cdce8p committed Apr 21, 2021
1 parent 0d086fa commit f6c38fa
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
4 changes: 4 additions & 0 deletions ChangeLog
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ Release Date: TBA

* Added inference tip for ``typing.Tuple`` alias

* Fix crash when evaluating ``typing.NamedTuple``

Closes PyCQA/pylint#4383


What's New in astroid 2.5.3?
============================
Expand Down
3 changes: 2 additions & 1 deletion astroid/brain/brain_namedtuple_enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -473,7 +473,8 @@ def infer_typing_namedtuple(node, context=None):
MANAGER.register_transform(
nodes.FunctionDef,
inference_tip(infer_typing_namedtuple_function),
lambda node: node.name == "NamedTuple" and node.parent.name == "typing",
lambda node: node.name == "NamedTuple"
and getattr(node.root(), "name", None) == "typing",
)
MANAGER.register_transform(
nodes.Call, inference_tip(infer_typing_namedtuple), _looks_like_typing_namedtuple
Expand Down
26 changes: 26 additions & 0 deletions tests/unittest_brain.py
Original file line number Diff line number Diff line change
Expand Up @@ -1321,6 +1321,32 @@ class Example(NamedTuple):
const = next(class_attr.infer())
self.assertEqual(const.value, "class_attr")

def test_namedtuple_inferred_as_class(self):
node = builder.extract_node(
"""
from typing import NamedTuple
NamedTuple
"""
)
inferred = next(node.infer())
assert isinstance(inferred, nodes.ClassDef)
assert inferred.name == "NamedTuple"

def test_namedtuple_bug_pylint_4383(self):
"""Inference of 'NamedTuple' function shouldn't cause InferenceError.
https://github.com/PyCQA/pylint/issues/4383
"""
node = builder.extract_node(
"""
if True:
def NamedTuple():
pass
NamedTuple
"""
)
next(node.infer())

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

0 comments on commit f6c38fa

Please sign in to comment.