Skip to content

Commit 86b8c64

Browse files
Fix crash when using enumerate with start and a class attribute (#7824)
Co-authored-by: Pierre Sassoulas <[email protected]>
1 parent ebf2824 commit 86b8c64

File tree

3 files changed

+29
-9
lines changed

3 files changed

+29
-9
lines changed

doc/whatsnew/fragments/7821.bugfix

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fixes a crash in the ``unnecessary_list_index_lookup`` check when using ``enumerate`` with ``start`` and a class attribute.
2+
3+
Closes #7821

pylint/checkers/refactoring/refactoring_checker.py

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2248,15 +2248,13 @@ def _enumerate_with_start(
22482248
return False, confidence
22492249

22502250
def _get_start_value(self, node: nodes.NodeNG) -> tuple[int | None, Confidence]:
2251-
confidence = HIGH
2252-
2253-
if isinstance(node, (nodes.Name, nodes.Call)):
2251+
if isinstance(node, (nodes.Name, nodes.Call, nodes.Attribute)):
22542252
inferred = utils.safe_infer(node)
22552253
start_val = inferred.value if inferred else None
2256-
confidence = INFERENCE
2257-
elif isinstance(node, nodes.UnaryOp):
2258-
start_val = node.operand.value
2259-
else:
2260-
start_val = node.value
2254+
return start_val, INFERENCE
2255+
if isinstance(node, nodes.UnaryOp):
2256+
return node.operand.value, HIGH
2257+
if isinstance(node, nodes.Const):
2258+
return node.value, HIGH
22612259

2262-
return start_val, confidence
2260+
return None, HIGH

tests/functional/u/unnecessary/unnecessary_list_index_lookup.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,3 +130,22 @@ def return_start(start):
130130

131131
for i, k in enumerate(series, return_start(20)):
132132
print(series[idx])
133+
134+
for idx, val in enumerate(iterable=series, start=0):
135+
print(series[idx]) # [unnecessary-list-index-lookup]
136+
137+
result = [my_list[idx] for idx, val in enumerate(iterable=my_list)] # [unnecessary-list-index-lookup]
138+
139+
for idx, val in enumerate():
140+
print(my_list[idx])
141+
142+
class Command:
143+
def _get_extra_attrs(self, extra_columns):
144+
self.extra_rows_start = 8 # pylint: disable=attribute-defined-outside-init
145+
for index, column in enumerate(extra_columns, start=self.extra_rows_start):
146+
pass
147+
148+
Y_START = 2
149+
nums = list(range(20))
150+
for y, x in enumerate(nums, start=Y_START + 1):
151+
pass

0 commit comments

Comments
 (0)