Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix undefined-loop-variable from walrus in comprehension test #7324

Merged
merged 2 commits into from
Aug 20, 2022
Merged
Show file tree
Hide file tree
Changes from all 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/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
18 changes: 18 additions & 0 deletions pylint/checkers/variables.py
Original file line number Diff line number Diff line change
Expand Up @@ -2249,6 +2249,24 @@ 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
)
if comprehension_scope is None:
# Should not be possible.
pass
elif (
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
8 changes: 8 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,8 @@
"""Tests for undefined-loop-variable with assignment expressions"""


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)])
2 changes: 2 additions & 0 deletions tests/functional/u/undefined/undefined_loop_variable_py38.rc
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[testoptions]
min_pyver=3.8