diff options
author | Jacob Walls <jacobtylerwalls@gmail.com> | 2022-05-13 10:07:05 -0400 |
---|---|---|
committer | Pierre Sassoulas <pierre.sassoulas@gmail.com> | 2022-05-13 17:30:49 +0200 |
commit | 7d80ca5bdbbb0aea4da504ba8abc984f1530fd80 (patch) | |
tree | 99235c8e1529f7dded8f821e9ca3adf4bd18cff2 | |
parent | 9c2fe99946af40478e366dc852545ddb90559822 (diff) | |
download | pylint-git-7d80ca5bdbbb0aea4da504ba8abc984f1530fd80.tar.gz |
Fix false positive for `undefined-loop-variable` with `enumerate()` (#6602)
Co-authored-by: Pierre Sassoulas <pierre.sassoulas@gmail.com>
-rw-r--r-- | ChangeLog | 4 | ||||
-rw-r--r-- | doc/whatsnew/2.13.rst | 4 | ||||
-rw-r--r-- | pylint/checkers/variables.py | 7 | ||||
-rw-r--r-- | tests/functional/u/undefined/undefined_loop_variable.py | 7 |
4 files changed, 22 insertions, 0 deletions
@@ -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? ============================ diff --git a/doc/whatsnew/2.13.rst b/doc/whatsnew/2.13.rst index 1ae1ca7f9..e5a628d8a 100644 --- a/doc/whatsnew/2.13.rst +++ b/doc/whatsnew/2.13.rst @@ -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 diff --git a/pylint/checkers/variables.py b/pylint/checkers/variables.py index 807e031e6..fb50f4501 100644 --- a/pylint/checkers/variables.py +++ b/pylint/checkers/variables.py @@ -2265,6 +2265,13 @@ class VariablesChecker(BaseChecker): # 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: diff --git a/tests/functional/u/undefined/undefined_loop_variable.py b/tests/functional/u/undefined/undefined_loop_variable.py index 6bcf6103d..d66bd5a05 100644 --- a/tests/functional/u/undefined/undefined_loop_variable.py +++ b/tests/functional/u/undefined/undefined_loop_variable.py @@ -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) |