Skip to content

Commit

Permalink
Skip PERF203 violations for multi-statement loops (#6145)
Browse files Browse the repository at this point in the history
Closes #5858.
  • Loading branch information
charliermarsh authored Jul 28, 2023
1 parent d154364 commit cd41474
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 39 deletions.
15 changes: 5 additions & 10 deletions crates/ruff/resources/test/fixtures/perflint/PERF203.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,23 @@
# PERF203
for i in range(10):
try: # PERF203
try:
print(f"{i}")
except:
print("error")

# OK
try:
for i in range(10):
print(f"{i}")
except:
print("error")

# OK
i = 0
while i < 10: # PERF203
while i < 10:
try:
print(f"{i}")
except:
print("error")

i += 1

try:
i = 0
while i < 10:
print(f"{i}")
i += 1
except:
print("error")
21 changes: 11 additions & 10 deletions crates/ruff/src/rules/perflint/rules/try_except_in_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,14 +67,15 @@ pub(crate) fn try_except_in_loop(checker: &mut Checker, body: &[Stmt]) {
return;
}

checker.diagnostics.extend(body.iter().filter_map(|stmt| {
if let Stmt::Try(ast::StmtTry { handlers, .. }) = stmt {
handlers
.iter()
.next()
.map(|handler| Diagnostic::new(TryExceptInLoop, handler.range()))
} else {
None
}
}));
let [Stmt::Try(ast::StmtTry { handlers, .. })] = body else {
return;
};

let Some(handler) = handlers.first() else {
return;
};

checker
.diagnostics
.push(Diagnostic::new(TryExceptInLoop, handler.range()));
}
Original file line number Diff line number Diff line change
@@ -1,28 +1,16 @@
---
source: crates/ruff/src/rules/perflint/mod.rs
---
PERF203.py:4:5: PERF203 `try`-`except` within a loop incurs performance overhead
PERF203.py:5:5: PERF203 `try`-`except` within a loop incurs performance overhead
|
2 | try: # PERF203
3 | print(f"{i}")
4 | except:
3 | try:
4 | print(f"{i}")
5 | except:
| _____^
5 | | print("error")
6 | | print("error")
| |______________________^ PERF203
6 |
7 | try:
7 |
8 | # OK
|

PERF203.py:17:5: PERF203 `try`-`except` within a loop incurs performance overhead
|
15 | try:
16 | print(f"{i}")
17 | except:
| _____^
18 | | print("error")
| |______________________^ PERF203
19 |
20 | i += 1
|


0 comments on commit cd41474

Please sign in to comment.