Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[unnecessary-list-index-lookup] Fix crashes for uninferrable 'start' value in 'enumerate' #9704

Merged
merged 3 commits into from
Jun 6, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
6 changes: 5 additions & 1 deletion pylint/checkers/refactoring/refactoring_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -2454,7 +2454,11 @@ 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
start_val = None
if inferred and isinstance(inferred, nodes.Const):
Pierre-Sassoulas marked this conversation as resolved.
Show resolved Hide resolved
# inferred can be an astroid.base.Instance not only a nodes.Const,
# as in 'enumerate(x, int(y))'
start_val = inferred.value
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])):
...
Loading