From 21820c62cf1dce002a7f707c893911a6ebf2e024 Mon Sep 17 00:00:00 2001 From: cpopa Date: Sun, 21 Jul 2013 16:50:24 +0300 Subject: Add support for unbalanced tuple unpacking check. --- checkers/variables.py | 26 ++++++++++++++++++++++++++ test/input/func_w0632.py | 8 ++++++++ test/messages/func_w0632.txt | 1 + 3 files changed, 35 insertions(+) create mode 100644 test/input/func_w0632.py create mode 100644 test/messages/func_w0632.txt diff --git a/checkers/variables.py b/checkers/variables.py index 07156d1..e59a304 100644 --- a/checkers/variables.py +++ b/checkers/variables.py @@ -118,6 +118,12 @@ MSGS = { 'Used when an loop variable (i.e. defined by a for loop or \ a list comprehension or a generator expression) is used outside \ the loop.'), + + 'W0632': ('Possible unbalanced tuple unpacking: ' + 'left side has %d label(s), right side has %d value(s)', + 'unbalanced-tuple-unpacking', + 'Used when there is an unbalanced tuple unpacking in assignment'), + } class VariablesChecker(BaseChecker): @@ -536,6 +542,26 @@ builtins. Remember that you should avoid to define new builtins when possible.' continue self._check_module_attrs(node, module, name.split('.')) + @check_messages('W0632') + def visit_assign(self, node): + """ Check unbalanced tuple unpacking for assignments. """ + if not isinstance(node.value, astroid.Tuple): + return + if not isinstance(node.targets[0], astroid.Tuple): + return + + targets = node.targets[0].itered() + values = node.value.itered() + + if any(not isinstance(target_node, astroid.AssName) + for target_node in targets): + return + + if len(targets) != len(values): + self.add_message('W0632', + node=node, + args=(len(targets), len(values))) + def _check_module_attrs(self, node, module, module_names): """check that module_names (list of string) are accessible through the given module diff --git a/test/input/func_w0632.py b/test/input/func_w0632.py new file mode 100644 index 0000000..6437a50 --- /dev/null +++ b/test/input/func_w0632.py @@ -0,0 +1,8 @@ +"""Check possible unbalanced tuple unpacking """ + +__revision__ = 0 + +def do_stuff(): + """This is not right.""" + first, second = 1, 2, 3 + return first + second diff --git a/test/messages/func_w0632.txt b/test/messages/func_w0632.txt new file mode 100644 index 0000000..c4c2d03 --- /dev/null +++ b/test/messages/func_w0632.txt @@ -0,0 +1 @@ +W: 7:do_stuff: Possible unbalanced tuple unpacking: left side has 2 label(s), right side has 3 value(s) \ No newline at end of file -- cgit v1.2.1