Skip to content

Commit

Permalink
Fix a crash on namedtuples that use typename (#1773)
Browse files Browse the repository at this point in the history
Co-authored-by: Pierre Sassoulas <pierre.sassoulas@gmail.com>
  • Loading branch information
DanielNoord and Pierre-Sassoulas committed Sep 7, 2022
1 parent 65bca39 commit 13469d2
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
3 changes: 3 additions & 0 deletions ChangeLog
Expand Up @@ -12,6 +12,9 @@ What's New in astroid 2.12.9?
=============================
Release date: TBA

* Fixed a crash on ``namedtuples`` that use ``typename`` to specify their name.

Closes PyCQA/pylint#7429



Expand Down
12 changes: 12 additions & 0 deletions astroid/brain/brain_namedtuple_enum.py
Expand Up @@ -538,10 +538,22 @@ def _get_namedtuple_fields(node: nodes.Call) -> str:
extract a node from them later on.
"""
names = []
container = None
try:
container = next(node.args[1].infer())
except (InferenceError, StopIteration) as exc:
raise UseInferenceDefault from exc
# We pass on IndexError as we'll try to infer 'field_names' from the keywords
except IndexError:
pass
if not container:
for keyword_node in node.keywords:
if keyword_node.arg == "field_names":
try:
container = next(keyword_node.value.infer())
except (InferenceError, StopIteration) as exc:
raise UseInferenceDefault from exc
break
if not isinstance(container, nodes.BaseContainer):
raise UseInferenceDefault
for elt in container.elts:
Expand Down
17 changes: 17 additions & 0 deletions tests/unittest_brain.py
Expand Up @@ -434,6 +434,23 @@ def __str__(self):
inferred = next(node.infer())
self.assertIs(util.Uninferable, inferred)

def test_name_as_typename(self) -> None:
"""Reported in https://github.com/PyCQA/pylint/issues/7429 as a crash."""
good_node, good_node_two, bad_node = builder.extract_node(
"""
import collections
collections.namedtuple(typename="MyTuple", field_names=["birth_date", "city"]) #@
collections.namedtuple("MyTuple", field_names=["birth_date", "city"]) #@
collections.namedtuple(["birth_date", "city"], typename="MyTuple") #@
"""
)
good_inferred = next(good_node.infer())
assert isinstance(good_inferred, nodes.ClassDef)
good_node_two_inferred = next(good_node_two.infer())
assert isinstance(good_node_two_inferred, nodes.ClassDef)
bad_node_inferred = next(bad_node.infer())
assert bad_node_inferred == util.Uninferable


class DefaultDictTest(unittest.TestCase):
def test_1(self) -> None:
Expand Down

0 comments on commit 13469d2

Please sign in to comment.