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 with enumerate() #6602

Merged
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 4 additions & 0 deletions ChangeLog
Expand Up @@ -335,6 +335,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 @@ -2220,6 +2220,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)