Skip to content

Commit

Permalink
Respect start index in unnecessary-list-index-lookup (#12603)
Browse files Browse the repository at this point in the history
## Summary

Closes #12594.
  • Loading branch information
charliermarsh committed Aug 1, 2024
1 parent 3f49ab1 commit 8e383b9
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,17 @@ def value_intentionally_unused():
print(letters[index]) # OK
blah = letters[index] # OK
letters[index] = "d" # OK


def start():
# OK
for index, list_item in enumerate(some_list, start=1):
print(some_list[index])

# PLR1736
for index, list_item in enumerate(some_list, start=0):
print(some_list[index])

# PLR1736
for index, list_item in enumerate(some_list):
print(some_list[index])
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use ruff_diagnostics::{AlwaysFixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::visitor::Visitor;
use ruff_python_ast::{self as ast, Expr, StmtFor};
use ruff_python_ast::{self as ast, Expr, Int, Number, StmtFor};
use ruff_python_semantic::SemanticModel;
use ruff_text_size::Ranged;

Expand Down Expand Up @@ -151,6 +151,19 @@ fn enumerate_items<'a>(
return None;
};

// If the `enumerate` call has a non-zero `start`, don't omit.
if !arguments.find_argument("start", 1).map_or(true, |expr| {
matches!(
expr,
Expr::NumberLiteral(ast::ExprNumberLiteral {
value: Number::Int(Int::ZERO),
..
})
)
}) {
return None;
}

// Check that the function is the `enumerate` builtin.
if !semantic.match_builtin_expr(func, "enumerate") {
return None;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,3 +181,40 @@ unnecessary_list_index_lookup.py:19:16: PLR1736 [*] List index lookup in `enumer
20 20 |
21 21 |
22 22 | def dont_fix_these():

unnecessary_list_index_lookup.py:74:15: PLR1736 [*] List index lookup in `enumerate()` loop
|
72 | # PLR1736
73 | for index, list_item in enumerate(some_list, start=0):
74 | print(some_list[index])
| ^^^^^^^^^^^^^^^^ PLR1736
75 |
76 | # PLR1736
|
= help: Use the loop variable directly

Safe fix
71 71 |
72 72 | # PLR1736
73 73 | for index, list_item in enumerate(some_list, start=0):
74 |- print(some_list[index])
74 |+ print(list_item)
75 75 |
76 76 | # PLR1736
77 77 | for index, list_item in enumerate(some_list):

unnecessary_list_index_lookup.py:78:15: PLR1736 [*] List index lookup in `enumerate()` loop
|
76 | # PLR1736
77 | for index, list_item in enumerate(some_list):
78 | print(some_list[index])
| ^^^^^^^^^^^^^^^^ PLR1736
|
= help: Use the loop variable directly

Safe fix
75 75 |
76 76 | # PLR1736
77 77 | for index, list_item in enumerate(some_list):
78 |- print(some_list[index])
78 |+ print(list_item)

0 comments on commit 8e383b9

Please sign in to comment.