Skip to content

Commit 16fe127

Browse files
fix: handle for-loop variable shadowing correctly (#10569) (#10571)
(cherry picked from commit ed6b306) Signed-off-by: Emmanuel Ferdman <emmanuelferdman@gmail.com> Co-authored-by: Emmanuel Ferdman <emmanuelferdman@gmail.com>
1 parent 6cf727c commit 16fe127

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
@@ -629,7 +629,12 @@ def get_next_to_consume(self, node: nodes.Name) -> list[nodes.NodeNG] | None:
629629
and parent_node.iter == node
630630
and parent_node.target in found_nodes
631631
):
632-
found_nodes = None
632+
# Only filter out the for-loop target if there are other definitions besides the target
633+
other_definitions = [fn for fn in found_nodes if fn != parent_node.target]
634+
if other_definitions:
635+
found_nodes = other_definitions
636+
else:
637+
found_nodes = None
633638

634639
# Before filtering, check that this node's name is not a nonlocal
635640
if any(
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)