summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorClaudiu Popa <cpopa@cloudbasesolutions.com>2015-02-21 18:49:43 +0200
committerClaudiu Popa <cpopa@cloudbasesolutions.com>2015-02-21 18:49:43 +0200
commit7ef2825be4eaf208df22226de3419ec591553bdf (patch)
treeca5fb539a31dc71a4ac56641ac74deefe4fe705f
parent7062462e5b26132f5d479bfdaef68222dba0b04b (diff)
downloadastroid-git-7ef2825be4eaf208df22226de3419ec591553bdf.tar.gz
Implement the assigned_stmts operation for Starred nodes.
This was omitted when support for Python 3 was added in astroid. It currently works only for Starred nodes in assignments and only for the most common of cases, such as `a, *b = (1, 2, 3)`. Closes issue #36.
-rw-r--r--ChangeLog6
-rw-r--r--astroid/protocols.py53
-rw-r--r--astroid/tests/unittest_protocols.py153
3 files changed, 211 insertions, 1 deletions
diff --git a/ChangeLog b/ChangeLog
index 5adc6a6b..5973b2cd 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -22,7 +22,11 @@ Change log for the astroid package (used to be astng)
which was also an import and which had, as a base, a qualified name
or a Gettattr node, in the form 'module.first', then Pylint would
have inferred the `first` name as the function from the Class,
- not the import. Closes Pylint issue #466.
+ not the import. Closes Pylint issue #466.
+
+ * Implement the assigned_stmts operation for Starred nodes,
+ which was omitted when support for Python 3 was added in astroid.
+ Closes issue #36.
2015-01-17 -- 1.3.4
diff --git a/astroid/protocols.py b/astroid/protocols.py
index 4dd515fd..5b554118 100644
--- a/astroid/protocols.py
+++ b/astroid/protocols.py
@@ -20,6 +20,7 @@ where it makes sense.
"""
__doctype__ = "restructuredtext en"
+import collections
from astroid.exceptions import InferenceError, NoDefault, NotFoundError
from astroid.node_classes import unpack_infer
@@ -359,3 +360,55 @@ def with_assigned_stmts(self, node, context=None, asspath=None):
nodes.With.assigned_stmts = raise_if_nothing_infered(with_assigned_stmts)
+def starred_assigned_stmts(self, node=None, context=None, asspath=None):
+ stmt = self.statement()
+ if not isinstance(stmt, (nodes.Assign, nodes.For)):
+ raise InferenceError()
+
+ if isinstance(stmt, nodes.Assign):
+ value = stmt.value
+ lhs = stmt.targets[0]
+
+ if sum(1 for node in lhs.nodes_of_class(nodes.Starred)) > 1:
+ # Too many starred arguments in the expression.
+ raise InferenceError()
+
+ if context is None:
+ context = InferenceContext()
+ try:
+ rhs = next(value.infer(context))
+ except InferenceError:
+ yield YES
+ return
+ if rhs is YES or not hasattr(rhs, 'elts'):
+ # Not interested in inferred values without elts.
+ yield YES
+ return
+
+ elts = collections.deque(rhs.elts[:])
+ if len(lhs.elts) > len(rhs.elts):
+ # a, *b, c = (1, 2)
+ raise InferenceError()
+
+ # Unpack iteratively the values from the rhs of the assignment,
+ # until the find the starred node. What will remain will
+ # be the list of values which the Starred node will represent
+ # This is done in two steps, from left to right to remove
+ # anything before the starred node and from right to left
+ # to remvoe anything after the starred node.
+
+ for index, node in enumerate(lhs.elts):
+ if not isinstance(node, nodes.Starred):
+ elts.popleft()
+ continue
+ lhs_elts = collections.deque(reversed(lhs.elts[index:]))
+ for node in lhs_elts:
+ if not isinstance(node, nodes.Starred):
+ elts.pop()
+ continue
+ # We're done
+ for elt in elts:
+ yield elt
+ break
+
+nodes.Starred.assigned_stmts = starred_assigned_stmts
diff --git a/astroid/tests/unittest_protocols.py b/astroid/tests/unittest_protocols.py
new file mode 100644
index 00000000..e8f387ff
--- /dev/null
+++ b/astroid/tests/unittest_protocols.py
@@ -0,0 +1,153 @@
+# copyright 2003-2015 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
+# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
+#
+# This file is part of astroid.
+#
+# astroid is free software: you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as published by the
+# Free Software Foundation, either version 2.1 of the License, or (at your
+# option) any later version.
+#
+# astroid is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+# for more details.
+#
+# You should have received a copy of the GNU Lesser General Public License along
+# with astroid. If not, see <http://www.gnu.org/licenses/>.
+
+import unittest
+
+from astroid import YES
+from astroid.test_utils import extract_node, require_version
+from astroid import InferenceError
+from astroid.node_classes import AssName, Const, Name, Starred
+
+
+class ProtocolTests(unittest.TestCase):
+
+ def assertConstNodesEqual(self, nodes_list_expected, nodes_list_got):
+ self.assertEqual(len(nodes_list_expected), len(nodes_list_got))
+ for node in nodes_list_got:
+ self.assertIsInstance(node, Const)
+ for node, expected_value in zip(nodes_list_got, nodes_list_expected):
+ self.assertEqual(expected_value, node.value)
+
+ def assertNameNodesEqual(self, nodes_list_expected, nodes_list_got):
+ self.assertEqual(len(nodes_list_expected), len(nodes_list_got))
+ for node in nodes_list_got:
+ self.assertIsInstance(node, Name)
+ for node, expected_name in zip(nodes_list_got, nodes_list_expected):
+ self.assertEqual(expected_name, node.name)
+
+ def test_assigned_stmts_simple_for(self):
+ assign_stmts = extract_node("""
+ for a in (1, 2, 3): #@
+ pass
+
+ for b in range(3): #@
+ pass
+ """)
+
+ for1_assnode = next(assign_stmts[0].nodes_of_class(AssName))
+ assigned = list(for1_assnode.assigned_stmts())
+ self.assertConstNodesEqual([1, 2, 3], assigned)
+
+ for2_assnode = next(assign_stmts[1].nodes_of_class(AssName))
+ self.assertRaises(InferenceError,
+ list, for2_assnode.assigned_stmts())
+
+ @require_version(minver='3.0')
+ def test_assigned_stmts_starred_for(self):
+ assign_stmts = extract_node("""
+ for *a, b in ((1, 2, 3), (4, 5, 6, 7)): #@
+ pass
+ """)
+
+ for1_starred = next(assign_stmts.nodes_of_class(Starred))
+ assigned = list(for1_starred.assigned_stmts())
+ self.assertEqual(assigned, [])
+
+ def _get_starred_stmts(self, code, expected):
+ assign_stmt = extract_node("{} #@".format(code))
+ starred = next(assign_stmt.nodes_of_class(Starred))
+ return list(starred.assigned_stmts())
+
+ def _helper_starred_expected_const(self, code, expected):
+ stmts = self._get_starred_stmts(code, expected)
+ self.assertConstNodesEqual(expected, stmts)
+
+ def _helper_starred_expected(self, code, expected):
+ stmts = self._get_starred_stmts(code, expected)
+ self.assertEqual(expected, stmts)
+
+ def _helper_starred_inference_error(self, code):
+ assign_stmt = extract_node("{} #@".format(code))
+ starred = next(assign_stmt.nodes_of_class(Starred))
+ self.assertRaises(InferenceError, list, starred.assigned_stmts())
+
+ @require_version(minver='3.0')
+ def test_assigned_stmts_starred_assnames(self):
+ self._helper_starred_expected_const(
+ "a, *b = (1, 2, 3, 4) #@", [2, 3, 4])
+ self._helper_starred_expected_const(
+ "*a, b = (1, 2, 3) #@", [1, 2])
+ self._helper_starred_expected_const(
+ "a, *b, c = (1, 2, 3, 4, 5) #@",
+ [2, 3, 4])
+ self._helper_starred_expected_const(
+ "a, *b = (1, 2) #@", [2])
+ self._helper_starred_expected_const(
+ "*b, a = (1, 2) #@", [1])
+ self._helper_starred_expected_const(
+ "[*b] = (1, 2) #@", [1, 2])
+
+ @require_version(minver='3.0')
+ def test_assigned_stmts_starred_yes(self):
+ # Not something iterable and known
+ self._helper_starred_expected("a, *b = range(3) #@", [YES])
+ # Not something inferrable
+ self._helper_starred_expected("a, *b = balou() #@", [YES])
+ # In function, unknown.
+ self._helper_starred_expected("""
+ def test(arg):
+ head, *tail = arg #@""", [YES])
+ # These cases aren't worth supporting.
+ self._helper_starred_expected(
+ "a, (*b, c), d = (1, (2, 3, 4), 5) #@", [])
+
+ @require_version(minver='3.0')
+ def test_assign_stmts_starred_fails(self):
+ # Too many starred
+ self._helper_starred_inference_error("a, *b, *c = (1, 2, 3) #@")
+ # Too many lhs values
+ self._helper_starred_inference_error("a, *b, c = (1, 2) #@")
+ # Not in Assign or For
+ self._helper_starred_inference_error("[*b for b in (1, 2, 3)] #@")
+ # This could be solved properly, but it complicates needlessly the
+ # code for assigned_stmts, without oferring real benefit.
+ self._helper_starred_inference_error(
+ "(*a, b), (c, *d) = (1, 2, 3), (4, 5, 6) #@")
+
+ def test_assigned_stmts_assignments(self):
+ assign_stmts = extract_node("""
+ c = a #@
+
+ d, e = b, c #@
+ """)
+
+ simple_assnode = next(assign_stmts[0].nodes_of_class(AssName))
+ assigned = list(simple_assnode.assigned_stmts())
+ self.assertNameNodesEqual(['a'], assigned)
+
+ assnames = assign_stmts[1].nodes_of_class(AssName)
+ simple_mul_assnode_1 = next(assnames)
+ assigned = list(simple_mul_assnode_1.assigned_stmts())
+ self.assertNameNodesEqual(['b'], assigned)
+ simple_mul_assnode_2 = next(assnames)
+ assigned = list(simple_mul_assnode_2.assigned_stmts())
+ self.assertNameNodesEqual(['c'], assigned)
+
+
+if __name__ == '__main__':
+ unittest.main()