Skip to content

Commit c3e2579

Browse files
[unnecessary-list-index-lookup] Fix crashes for uninferrable 'start' value in 'enumerate' (#9704) (#9707)
--------- Co-authored-by: Daniël van Noord <[email protected]> (cherry picked from commit 9f8dcbd) Co-authored-by: Pierre Sassoulas <[email protected]>
1 parent 6b66ca6 commit c3e2579

File tree

3 files changed

+18
-1
lines changed

3 files changed

+18
-1
lines changed

doc/whatsnew/fragments/9078.bugfix

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Fixed a crash when the ``start`` value in an ``enumerate`` was non-constant and impossible to infer
2+
(like in``enumerate(apples, start=int(random_apple_index)``) for ``unnecessary-list-index-lookup``.
3+
4+
Closes #9078

pylint/checkers/refactoring/refactoring_checker.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2454,7 +2454,9 @@ def _get_start_value(self, node: nodes.NodeNG) -> tuple[int | None, Confidence]:
24542454
and isinstance(node.operand, (nodes.Attribute, nodes.Name))
24552455
):
24562456
inferred = utils.safe_infer(node)
2457-
start_val = inferred.value if inferred else None
2457+
# inferred can be an astroid.base.Instance as in 'enumerate(x, int(y))' or
2458+
# not correctly inferred (None)
2459+
start_val = inferred.value if isinstance(inferred, nodes.Const) else None
24582460
return start_val, INFERENCE
24592461
if isinstance(node, nodes.UnaryOp):
24602462
return node.operand.value, HIGH

tests/functional/u/unnecessary/unnecessary_list_index_lookup.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,3 +156,14 @@ def _get_extra_attrs(self, extra_columns):
156156
for idx, val in enumerate(my_list):
157157
if (val := 42) and my_list[idx] == 'b':
158158
print(1)
159+
160+
def regression_9078(apples, cant_infer_this):
161+
"""Regression test for https://github.com/pylint-dev/pylint/issues/9078."""
162+
for _, _ in enumerate(apples, int(cant_infer_this)):
163+
...
164+
165+
def random_uninferrable_start(pears):
166+
import random # pylint: disable=import-outside-toplevel
167+
168+
for _, _ in enumerate(pears, random.choice([5, 42])):
169+
...

0 commit comments

Comments
 (0)