Skip to content

Commit

Permalink
Fix false positive for undefined-loop-variable with enumerate() (#…
Browse files Browse the repository at this point in the history
…6602)


Co-authored-by: Pierre Sassoulas <pierre.sassoulas@gmail.com>
  • Loading branch information
jacobtylerwalls and Pierre-Sassoulas committed May 13, 2022
1 parent 9c2fe99 commit 7d80ca5
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 0 deletions.
4 changes: 4 additions & 0 deletions ChangeLog
Expand Up @@ -41,6 +41,10 @@ Release date: TBA

Closes #6539

* Fix a false positive for ``undefined-loop-variable`` when using ``enumerate()``.

Closes #6593


What's New in Pylint 2.13.8?
============================
Expand Down
4 changes: 4 additions & 0 deletions doc/whatsnew/2.13.rst
Expand Up @@ -657,3 +657,7 @@ Other Changes
* Fix a crash in ``unnecessary-dict-index-lookup`` when subscripting an attribute.

Closes #6557

* Fix a false positive for ``undefined-loop-variable`` when using ``enumerate()``.

Closes #6593
7 changes: 7 additions & 0 deletions pylint/checkers/variables.py
Expand Up @@ -2265,6 +2265,13 @@ def _loopvar_name(self, node: astroid.Name) -> None:
# For functions we can do more by inferring the length of the itered object
try:
inferred = next(assign.iter.infer())
# Prefer the target of enumerate() rather than the enumerate object itself
if (
isinstance(inferred, astroid.Instance)
and inferred.qname() == "builtins.enumerate"
and assign.iter.args
):
inferred = next(assign.iter.args[0].infer())
except astroid.InferenceError:
self.add_message("undefined-loop-variable", args=node.name, node=node)
else:
Expand Down
7 changes: 7 additions & 0 deletions tests/functional/u/undefined/undefined_loop_variable.py
Expand Up @@ -139,3 +139,10 @@ def variable_name_assigned_in_body_of_second_loop():
alias = True
if alias:
print(alias)


def use_enumerate():
"""https://github.com/PyCQA/pylint/issues/6593"""
for i, num in enumerate(range(3)):
pass
print(i, num)

0 comments on commit 7d80ca5

Please sign in to comment.