Skip to content

Commit eac2e04

Browse files
jacobtylerwallsPierre-Sassoulas
authored andcommitted
Fix crash when using enumerate in a ternary expression (#7132)
1 parent f1d27ff commit eac2e04

File tree

4 files changed

+18
-3
lines changed

4 files changed

+18
-3
lines changed

doc/whatsnew/2/2.14/full.rst

+5
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,11 @@ What's New in Pylint 2.14.5?
66
Release date: TBA
77

88

9+
* Fixed a crash in the ``undefined-loop-variable`` check when ``enumerate()`` is used
10+
in a ternary expression.
11+
12+
Closes #7131
13+
914
* Fixed handling of ``--`` as separator between positional arguments and flags.
1015

1116
Closes #7003

pylint/checkers/variables.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -2233,9 +2233,12 @@ def _loopvar_name(self, node: astroid.Name) -> None:
22332233
if (
22342234
isinstance(inferred, astroid.Instance)
22352235
and inferred.qname() == "builtins.enumerate"
2236-
and assign.iter.args
22372236
):
2238-
inferred = next(assign.iter.args[0].infer())
2237+
likely_call = assign.iter
2238+
if isinstance(assign.iter, nodes.IfExp):
2239+
likely_call = assign.iter.body
2240+
if isinstance(likely_call, nodes.Call):
2241+
inferred = next(likely_call.args[0].infer())
22392242
except astroid.InferenceError:
22402243
self.add_message("undefined-loop-variable", args=node.name, node=node)
22412244
else:

tests/functional/u/undefined/undefined_loop_variable.py

+7
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,13 @@ def use_enumerate():
148148
print(i, num)
149149

150150

151+
def use_enumerate_in_ternary_expression():
152+
"""https://github.com/PyCQA/pylint/issues/7131"""
153+
for i, num in enumerate(range(3)) if __revision__ else enumerate(range(4)):
154+
pass
155+
print(i, num)
156+
157+
151158
def find_even_number(container):
152159
"""https://github.com/PyCQA/pylint/pull/6923#discussion_r895134495"""
153160
for something in container:
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
undefined-loop-variable:6:11:6:14:do_stuff:Using possibly undefined loop variable 'var':UNDEFINED
22
undefined-loop-variable:25:7:25:11::Using possibly undefined loop variable 'var1':UNDEFINED
33
undefined-loop-variable:75:11:75:14:do_stuff_with_redefined_range:Using possibly undefined loop variable 'var':UNDEFINED
4-
undefined-loop-variable:156:11:156:20:find_even_number:Using possibly undefined loop variable 'something':UNDEFINED
4+
undefined-loop-variable:163:11:163:20:find_even_number:Using possibly undefined loop variable 'something':UNDEFINED

0 commit comments

Comments
 (0)