Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions doc/whatsnew/fragments/10562.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix false positive ``undefined-variable`` (E0602) for for-loop variable shadowing patterns like ``for item in item:`` when the variable was previously defined.

Closes #10562
7 changes: 6 additions & 1 deletion pylint/checkers/variables.py
Original file line number Diff line number Diff line change
Expand Up @@ -585,7 +585,12 @@ def get_next_to_consume(self, node: nodes.Name) -> list[nodes.NodeNG] | None:
and parent_node.iter == node
and parent_node.target in found_nodes
):
found_nodes = None
# Only filter out the for-loop target if there are other definitions besides the target
other_definitions = [fn for fn in found_nodes if fn != parent_node.target]
if other_definitions:
found_nodes = other_definitions
else:
found_nodes = None

# Before filtering, check that this node's name is not a nonlocal
if _is_nonlocal_name(node, node.frame()):
Expand Down
10 changes: 10 additions & 0 deletions tests/functional/f/for_loop_variable_shadowing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# pylint: disable=missing-module-docstring

# Should not trigger undefined-variable (#10562)
item = (1, 2, 3)
for item in item:
print(item)

# Should trigger undefined-variable
for iteree in iteree: # [undefined-variable]
print(iteree)
1 change: 1 addition & 0 deletions tests/functional/f/for_loop_variable_shadowing.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
undefined-variable:9:14:9:20::Undefined variable 'iteree':UNDEFINED
Loading