Skip to content

Commit

Permalink
Fix crash when using enumerate in a ternary expression (pylint-dev#…
Browse files Browse the repository at this point in the history
  • Loading branch information
jacobtylerwalls authored and Pierre-Sassoulas committed Jul 17, 2022
1 parent 9af506a commit 3915922
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 3 deletions.
5 changes: 5 additions & 0 deletions doc/whatsnew/2/2.14/full.rst
Expand Up @@ -6,6 +6,11 @@ What's New in Pylint 2.14.5?
Release date: TBA


* Fixed a crash in the ``undefined-loop-variable`` check when ``enumerate()`` is used
in a ternary expression.

Closes #7131

* Fixed handling of ``--`` as separator between positional arguments and flags.

Closes #7003
Expand Down
7 changes: 5 additions & 2 deletions pylint/checkers/variables.py
Expand Up @@ -2233,9 +2233,12 @@ def _loopvar_name(self, node: astroid.Name) -> None:
if (
isinstance(inferred, astroid.Instance)
and inferred.qname() == "builtins.enumerate"
and assign.iter.args
):
inferred = next(assign.iter.args[0].infer())
likely_call = assign.iter
if isinstance(assign.iter, nodes.IfExp):
likely_call = assign.iter.body
if isinstance(likely_call, nodes.Call):
inferred = next(likely_call.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 @@ -148,6 +148,13 @@ def use_enumerate():
print(i, num)


def use_enumerate_in_ternary_expression():
"""https://github.com/PyCQA/pylint/issues/7131"""
for i, num in enumerate(range(3)) if __revision__ else enumerate(range(4)):
pass
print(i, num)


def find_even_number(container):
"""https://github.com/PyCQA/pylint/pull/6923#discussion_r895134495"""
for something in container:
Expand Down
2 changes: 1 addition & 1 deletion tests/functional/u/undefined/undefined_loop_variable.txt
@@ -1,4 +1,4 @@
undefined-loop-variable:6:11:6:14:do_stuff:Using possibly undefined loop variable 'var':UNDEFINED
undefined-loop-variable:25:7:25:11::Using possibly undefined loop variable 'var1':UNDEFINED
undefined-loop-variable:75:11:75:14:do_stuff_with_redefined_range:Using possibly undefined loop variable 'var':UNDEFINED
undefined-loop-variable:156:11:156:20:find_even_number:Using possibly undefined loop variable 'something':UNDEFINED
undefined-loop-variable:163:11:163:20:find_even_number:Using possibly undefined loop variable 'something':UNDEFINED

0 comments on commit 3915922

Please sign in to comment.