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 when a loop else raises or returns #6480

Merged
merged 2 commits into from
May 1, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
5 changes: 5 additions & 0 deletions ChangeLog
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,11 @@ Release date: TBA

Closes #6414

* Fix a false positive for ``undefined-loop-variable`` when the ``else`` of a ``for``
loop raises or returns.

Closes #5971


What's New in Pylint 2.13.7?
============================
Expand Down
5 changes: 5 additions & 0 deletions doc/whatsnew/2.13.rst
Original file line number Diff line number Diff line change
Expand Up @@ -607,6 +607,11 @@ Other Changes

Closes #5769

* Fix a false positive for ``undefined-loop-variable`` when the ``else`` of a ``for``
loop raises or returns.

Closes #5971

* Only raise ``not-callable`` when all the inferred values of a property are not callable.

Closes #5931
Expand Down
7 changes: 6 additions & 1 deletion pylint/checkers/variables.py
Original file line number Diff line number Diff line change
Expand Up @@ -2242,11 +2242,16 @@ def _loopvar_name(self, node: astroid.Name) -> None:
):
return

# For functions we can do more by inferring the length of the itered object
if not isinstance(assign, nodes.For):
self.add_message("undefined-loop-variable", args=node.name, node=node)
return
if any(
isinstance(else_stmt, (nodes.Return, nodes.Raise))
for else_stmt in assign.orelse
):
return

# For functions we can do more by inferring the length of the itered object
try:
inferred = next(assign.iter.infer())
except astroid.InferenceError:
Expand Down
16 changes: 16 additions & 0 deletions tests/functional/u/undefined/undefined_loop_variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,22 @@ def handle_line(layne):
handle_line(layne)


def for_else_returns(iterable):
for thing in iterable:
break
else:
return
print(thing)


def for_else_raises(iterable):
for thing in iterable:
break
else:
raise Exception
print(thing)


lst = []
lst2 = [1, 2, 3]

Expand Down