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

Skip PERF203 violations for multi-statement loops #6145

Merged
merged 1 commit into from
Jul 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
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
|


Loading