Skip to content

Commit ed6b306

Browse files
fix: handle for-loop variable shadowing correctly (#10569)
Signed-off-by: Emmanuel Ferdman <[email protected]>
1 parent 5b39db3 commit ed6b306

File tree

4 files changed

+20
-1
lines changed

4 files changed

+20
-1
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix false positive ``undefined-variable`` (E0602) for for-loop variable shadowing patterns like ``for item in item:`` when the variable was previously defined.
2+
3+
Closes #10562

pylint/checkers/variables.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -585,7 +585,12 @@ def get_next_to_consume(self, node: nodes.Name) -> list[nodes.NodeNG] | None:
585585
and parent_node.iter == node
586586
and parent_node.target in found_nodes
587587
):
588-
found_nodes = None
588+
# Only filter out the for-loop target if there are other definitions besides the target
589+
other_definitions = [fn for fn in found_nodes if fn != parent_node.target]
590+
if other_definitions:
591+
found_nodes = other_definitions
592+
else:
593+
found_nodes = None
589594

590595
# Before filtering, check that this node's name is not a nonlocal
591596
if _is_nonlocal_name(node, node.frame()):
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# pylint: disable=missing-module-docstring
2+
3+
# Should not trigger undefined-variable (#10562)
4+
item = (1, 2, 3)
5+
for item in item:
6+
print(item)
7+
8+
# Should trigger undefined-variable
9+
for iteree in iteree: # [undefined-variable]
10+
print(iteree)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
undefined-variable:9:14:9:20::Undefined variable 'iteree':UNDEFINED

0 commit comments

Comments
 (0)