From a3d86bd465775ad158c3372a99e8014bd33fd991 Mon Sep 17 00:00:00 2001 From: Claudiu Popa Date: Fri, 1 May 2020 08:22:28 +0200 Subject: [PATCH] Do not crash with SyntaxError when parsing namedtuples with invalid label Close PyCQA/pylint#3549 --- ChangeLog | 4 ++++ astroid/brain/brain_namedtuple_enum.py | 2 ++ tests/unittest_brain.py | 12 ++++++++++++ 3 files changed, 18 insertions(+) diff --git a/ChangeLog b/ChangeLog index c6dba270c..e5fd0d908 100644 --- a/ChangeLog +++ b/ChangeLog @@ -19,6 +19,10 @@ Release Date: TBA Close #779 +* Do not crash with SyntaxError when parsing namedtuples with invalid label + + Close PyCQA/pylint#3549 + What's New in astroid 2.4.0? ============================ diff --git a/astroid/brain/brain_namedtuple_enum.py b/astroid/brain/brain_namedtuple_enum.py index e590bbb79..13fcf793f 100644 --- a/astroid/brain/brain_namedtuple_enum.py +++ b/astroid/brain/brain_namedtuple_enum.py @@ -123,6 +123,8 @@ def infer_func_form(node, base_type, context=None, enum=False): except (AttributeError, exceptions.InferenceError): raise UseInferenceDefault() + attributes = [attr for attr in attributes if " " not in attr] + # If we can't infer the name of the class, don't crash, up to this point # we know it is a namedtuple anyway. name = name or "Uninferable" diff --git a/tests/unittest_brain.py b/tests/unittest_brain.py index cb11c4cf4..0a833664b 100644 --- a/tests/unittest_brain.py +++ b/tests/unittest_brain.py @@ -331,6 +331,18 @@ def test_namedtuple_bases_are_actually_names_not_nodes(self): self.assertIsInstance(inferred.bases[0], astroid.Name) self.assertEqual(inferred.bases[0].name, "tuple") + def test_invalid_label_does_not_crash_inference(self): + code = """ + import collections + a = collections.namedtuple( 'a', ['b c'] ) + a + """ + node = builder.extract_node(code) + inferred = next(node.infer()) + assert isinstance(inferred, astroid.ClassDef) + assert "b" not in inferred.locals + assert "c" not in inferred.locals + class DefaultDictTest(unittest.TestCase): def test_1(self):