Skip to content

Commit 5746f0d

Browse files
authored
Skip unnecessary-list-index-lookup if we encounter if statements (#7334)
1 parent e142ba8 commit 5746f0d

File tree

3 files changed

+21
-0
lines changed

3 files changed

+21
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
``unnecessary-list-index-lookup`` is now more conservative to avoid potential false positives.
2+
3+
Closes #6896

pylint/checkers/refactoring/refactoring_checker.py

+11
Original file line numberDiff line numberDiff line change
@@ -2127,6 +2127,15 @@ def _check_unnecessary_list_index_lookup(
21272127
)
21282128
has_nested_loops = next(nested_loops, None) is not None
21292129

2130+
# Check if there are any if statements within the loop in question;
2131+
# If so, we will be more conservative about reporting errors as we
2132+
# can't yet do proper control flow analysis to be sure when
2133+
# reassignment will affect us
2134+
if_statements = itertools.chain.from_iterable(
2135+
child.nodes_of_class(nodes.If) for child in children
2136+
)
2137+
has_if_statements = next(if_statements, None) is not None
2138+
21302139
for child in children:
21312140
for subscript in child.nodes_of_class(nodes.Subscript):
21322141
if isinstance(node, nodes.For) and _is_part_of_assignment_target(
@@ -2170,6 +2179,8 @@ def _check_unnecessary_list_index_lookup(
21702179
# loops we don't want to report this unless we get to the
21712180
# end of the loop without updating the collection
21722181
bad_nodes.append(subscript)
2182+
elif has_if_statements:
2183+
continue
21732184
else:
21742185
self.add_message(
21752186
"unnecessary-list-index-lookup",

tests/functional/u/unnecessary/unnecessary_list_index_lookup.py

+7
Original file line numberDiff line numberDiff line change
@@ -74,3 +74,10 @@ def process_list_again(data):
7474
print(updated_list[idx]) # [unnecessary-list-index-lookup]
7575
updated_list[idx] -= 1
7676
print(updated_list[idx])
77+
78+
# Regression test for https://github.com/PyCQA/pylint/issues/6896
79+
parts = ["a", "b", "c", "d"]
80+
for i, part in enumerate(parts):
81+
if i == 3: # more complex condition actually
82+
parts.insert(i, "X")
83+
print(part, parts[i])

0 commit comments

Comments
 (0)