Skip to content

Commit

Permalink
[unnecessary-list-index-lookup] Fix crashes for uninferrable 'start' …
Browse files Browse the repository at this point in the history
…value in 'enumerate' (#9704) (#9707)

---------

Co-authored-by: Daniël van Noord <13665637+DanielNoord@users.noreply.github.com>
(cherry picked from commit 9f8dcbd)

Co-authored-by: Pierre Sassoulas <pierre.sassoulas@gmail.com>
  • Loading branch information
github-actions[bot] and Pierre-Sassoulas committed Jun 6, 2024
1 parent 6b66ca6 commit c3e2579
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 1 deletion.
4 changes: 4 additions & 0 deletions doc/whatsnew/fragments/9078.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Fixed a crash when the ``start`` value in an ``enumerate`` was non-constant and impossible to infer
(like in``enumerate(apples, start=int(random_apple_index)``) for ``unnecessary-list-index-lookup``.

Closes #9078
4 changes: 3 additions & 1 deletion pylint/checkers/refactoring/refactoring_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -2454,7 +2454,9 @@ def _get_start_value(self, node: nodes.NodeNG) -> tuple[int | None, Confidence]:
and isinstance(node.operand, (nodes.Attribute, nodes.Name))
):
inferred = utils.safe_infer(node)
start_val = inferred.value if inferred else None
# inferred can be an astroid.base.Instance as in 'enumerate(x, int(y))' or
# not correctly inferred (None)
start_val = inferred.value if isinstance(inferred, nodes.Const) else None
return start_val, INFERENCE
if isinstance(node, nodes.UnaryOp):
return node.operand.value, HIGH
Expand Down
11 changes: 11 additions & 0 deletions tests/functional/u/unnecessary/unnecessary_list_index_lookup.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,3 +156,14 @@ def _get_extra_attrs(self, extra_columns):
for idx, val in enumerate(my_list):
if (val := 42) and my_list[idx] == 'b':
print(1)

def regression_9078(apples, cant_infer_this):
"""Regression test for https://github.com/pylint-dev/pylint/issues/9078."""
for _, _ in enumerate(apples, int(cant_infer_this)):
...

def random_uninferrable_start(pears):
import random # pylint: disable=import-outside-toplevel

for _, _ in enumerate(pears, random.choice([5, 42])):
...

0 comments on commit c3e2579

Please sign in to comment.