diff options
author | Torsten Marek <tmarek@google.com> | 2011-11-17 21:38:02 +0100 |
---|---|---|
committer | Torsten Marek <tmarek@google.com> | 2011-11-17 21:38:02 +0100 |
commit | df62bb8696ad499435fa9313cb71828dfd189a52 (patch) | |
tree | 16207cfa4355a58713e11a6dd12e3c1e1ac255b8 | |
parent | d3f545682f301e4b388bb9677ecab1ce51b2668c (diff) | |
download | pylint-git-df62bb8696ad499435fa9313cb71828dfd189a52.tar.gz |
Detect assignments to a loop variable in the else branch of a for statement.
Closes: #9188,#4024
-rw-r--r-- | ChangeLog | 3 | ||||
-rw-r--r-- | checkers/variables.py | 9 | ||||
-rw-r--r-- | test/input/func_w0631.py | 21 | ||||
-rw-r--r-- | test/messages/func_w0631.txt | 1 |
4 files changed, 33 insertions, 1 deletions
@@ -11,6 +11,9 @@ ChangeLog for PyLint * #50461, #52020, #51222: Do not issue warnings when using 2.6's property.setter/deleter functionality (patch by dneil@google.com) + * #9188, #4024: Do not trigger W0631 if a loop variable is assigned + in the else branch of a for loop. + 2011-10-07 -- 0.25.0 diff --git a/checkers/variables.py b/checkers/variables.py index 14bb1624e..484a9526f 100644 --- a/checkers/variables.py +++ b/checkers/variables.py @@ -28,6 +28,12 @@ from pylint.checkers.utils import (PYMETHODS, is_ancestor_name, is_builtin, is_defined_before, is_error, is_func_default, is_func_decorator, assign_parent, check_messages, is_inside_except, clobber_in_except) + +def in_for_else_branch(parent, stmt): + """Returns True if stmt in inside the else branch for a parent For stmt.""" + return (isinstance(parent, astng.For) and + any(else_stmt.parent_of(stmt) for else_stmt in parent.orelse)) + def overridden_method(klass, name): """get overridden method if any""" try: @@ -348,7 +354,8 @@ builtins. Remember that you should avoid to define new builtins when possible.' else: _astmts = astmts[:1] for i, stmt in enumerate(astmts[1:]): - if astmts[i].statement().parent_of(stmt): + if (astmts[i].statement().parent_of(stmt) + and not in_for_else_branch(astmts[i].statement(), stmt)): continue _astmts.append(stmt) astmts = _astmts diff --git a/test/input/func_w0631.py b/test/input/func_w0631.py new file mode 100644 index 000000000..2524f5e11 --- /dev/null +++ b/test/input/func_w0631.py @@ -0,0 +1,21 @@ +"""Check possible undefined loopvar +""" + +__revision__ = 0 + +def do_stuff(some_random_list): + """This is not right.""" + for var in some_random_list: + pass + print var + + +def do_else(some_random_list): + """This is not right.""" + for var in some_random_list: + if var == 42: + break + else: + var = 84 + print var + diff --git a/test/messages/func_w0631.txt b/test/messages/func_w0631.txt new file mode 100644 index 000000000..af335a178 --- /dev/null +++ b/test/messages/func_w0631.txt @@ -0,0 +1 @@ +W: 10:do_stuff: Using possibly undefined loop variable 'var' |