Skip to content

Commit 7d80ca5

Browse files
Fix false positive for undefined-loop-variable with enumerate() (#6602)
Co-authored-by: Pierre Sassoulas <[email protected]>
1 parent 9c2fe99 commit 7d80ca5

File tree

4 files changed

+22
-0
lines changed

4 files changed

+22
-0
lines changed

ChangeLog

+4
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,10 @@ Release date: TBA
4141

4242
Closes #6539
4343

44+
* Fix a false positive for ``undefined-loop-variable`` when using ``enumerate()``.
45+
46+
Closes #6593
47+
4448

4549
What's New in Pylint 2.13.8?
4650
============================

doc/whatsnew/2.13.rst

+4
Original file line numberDiff line numberDiff line change
@@ -657,3 +657,7 @@ Other Changes
657657
* Fix a crash in ``unnecessary-dict-index-lookup`` when subscripting an attribute.
658658

659659
Closes #6557
660+
661+
* Fix a false positive for ``undefined-loop-variable`` when using ``enumerate()``.
662+
663+
Closes #6593

pylint/checkers/variables.py

+7
Original file line numberDiff line numberDiff line change
@@ -2265,6 +2265,13 @@ def _loopvar_name(self, node: astroid.Name) -> None:
22652265
# For functions we can do more by inferring the length of the itered object
22662266
try:
22672267
inferred = next(assign.iter.infer())
2268+
# Prefer the target of enumerate() rather than the enumerate object itself
2269+
if (
2270+
isinstance(inferred, astroid.Instance)
2271+
and inferred.qname() == "builtins.enumerate"
2272+
and assign.iter.args
2273+
):
2274+
inferred = next(assign.iter.args[0].infer())
22682275
except astroid.InferenceError:
22692276
self.add_message("undefined-loop-variable", args=node.name, node=node)
22702277
else:

tests/functional/u/undefined/undefined_loop_variable.py

+7
Original file line numberDiff line numberDiff line change
@@ -139,3 +139,10 @@ def variable_name_assigned_in_body_of_second_loop():
139139
alias = True
140140
if alias:
141141
print(alias)
142+
143+
144+
def use_enumerate():
145+
"""https://github.com/PyCQA/pylint/issues/6593"""
146+
for i, num in enumerate(range(3)):
147+
pass
148+
print(i, num)

0 commit comments

Comments
 (0)