Skip to content

Commit

Permalink
Fix undefined-loop-variable from walrus in comprehension test
Browse files Browse the repository at this point in the history
  • Loading branch information
jacobtylerwalls committed Aug 20, 2022
1 parent 2e2f208 commit 07c91fd
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
3 changes: 3 additions & 0 deletions doc/whatsnew/fragments/7222.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix `undefined-loop-variable` from walrus in comprehension test.

Closes #7222
16 changes: 16 additions & 0 deletions pylint/checkers/variables.py
Original file line number Diff line number Diff line change
Expand Up @@ -2249,6 +2249,22 @@ def _loopvar_name(self, node: astroid.Name) -> None:
):
return

maybe_walrus = utils.get_node_first_ancestor_of_type(node, nodes.NamedExpr)
if maybe_walrus:
maybe_comprehension = utils.get_node_first_ancestor_of_type(
maybe_walrus, nodes.Comprehension
)
if maybe_comprehension:
comprehension_scope = utils.get_node_first_ancestor_of_type(
maybe_comprehension, nodes.ComprehensionScope
)
assert comprehension_scope is not None
if (
comprehension_scope.parent.scope() is scope
and node.name in comprehension_scope.locals
):
return

# For functions we can do more by inferring the length of the itered object
try:
inferred = next(assign.iter.infer())
Expand Down
5 changes: 5 additions & 0 deletions tests/functional/u/undefined/undefined_loop_variable_py38.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
def walrus_in_comprehension_test(container):
"""https://github.com/PyCQA/pylint/issues/7222"""
for something in container:
print(something)
print([my_test for something in container if (my_test := something)])

0 comments on commit 07c91fd

Please sign in to comment.