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 false positive for undefined-loop-variable for lambda in first of two loops #6479

Merged
merged 4 commits into from May 1, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions ChangeLog
Expand Up @@ -242,6 +242,11 @@ What's New in Pylint 2.13.8?
============================
Release date: TBA

* Fix a false positive for ``undefined-loop-variable`` for a variable used in a lambda
inside the first of multiple loops.

Closes #6419

* Fix a crash when linting a file that passes an integer ``mode=`` to
``open``

Expand Down
5 changes: 5 additions & 0 deletions doc/whatsnew/2.13.rst
Expand Up @@ -615,6 +615,11 @@ Other Changes

Closes #5930

* Fix a false positive for ``undefined-loop-variable`` for a variable used in a lambda
inside the first of multiple loops.

Closes #6419

* Fix a crash when linting a file that passes an integer ``mode=`` to
``open``

Expand Down
4 changes: 3 additions & 1 deletion pylint/checkers/variables.py
Expand Up @@ -2198,7 +2198,9 @@ def _loopvar_name(self, node: astroid.Name) -> None:
# the usage is safe because the function will not be defined either if
# the variable is not defined.
scope = node.scope()
if isinstance(scope, nodes.FunctionDef) and any(
# FunctionDef subclasses Lambda due to a curious ontology. Check both.
# See https://github.com/PyCQA/astroid/issues/291 (fix abandoned in a stale branch)
jacobtylerwalls marked this conversation as resolved.
Show resolved Hide resolved
if isinstance(scope, nodes.Lambda) and any(
asmt.scope().parent_of(scope) for asmt in astmts
):
return
Expand Down
20 changes: 20 additions & 0 deletions tests/functional/u/undefined/undefined_loop_variable.py
Expand Up @@ -103,3 +103,23 @@ def handle_line(layne):
]
for item in lst
]


def lambda_in_first_of_two_loops():
"""https://github.com/PyCQA/pylint/issues/6419"""
my_list = []
for thing in my_list:
print_it = lambda: print(thing) # pylint: disable=cell-var-from-loop
print_it()

for thing in my_list:
print(thing)


def variable_name_assigned_in_body_of_second_loop():
for alias in tuple(bigger):
continue
for _ in range(3):
alias = True
if alias:
print(alias)