diff --git a/doc/whatsnew/fragments/3044.bugfix b/doc/whatsnew/fragments/3044.bugfix new file mode 100644 index 0000000000..9f764ca4b5 --- /dev/null +++ b/doc/whatsnew/fragments/3044.bugfix @@ -0,0 +1,3 @@ +Fix bug in detecting ``unused-variable`` when iterating on variable. + +Closes #3044 diff --git a/pylint/checkers/variables.py b/pylint/checkers/variables.py index 38a3a7cc2a..a62d2362fc 100644 --- a/pylint/checkers/variables.py +++ b/pylint/checkers/variables.py @@ -2388,7 +2388,7 @@ def _check_is_unused( self._check_unused_arguments(name, node, stmt, argnames, nonlocal_names) else: if stmt.parent and isinstance( - stmt.parent, (nodes.Assign, nodes.AnnAssign, nodes.Tuple) + stmt.parent, (nodes.Assign, nodes.AnnAssign, nodes.Tuple, nodes.For) ): if name in nonlocal_names: return diff --git a/tests/functional/u/unused/unused_variable.py b/tests/functional/u/unused/unused_variable.py index f81fddefda..92a329f2f5 100644 --- a/tests/functional/u/unused/unused_variable.py +++ b/tests/functional/u/unused/unused_variable.py @@ -186,3 +186,16 @@ def sibling_except_handlers(): pass except ValueError as e: print(e) + +def func6(): + a = 1 + + def nonlocal_writer(): + nonlocal a + + for a in range(10): + pass + + nonlocal_writer() + + assert a == 9, a