Skip PERF203 violations for multi-statement loops (#6145)

Closes https://github.com/astral-sh/ruff/issues/5858.
This commit is contained in:
Charlie Marsh 2023-07-28 00:55:55 -04:00 committed by GitHub
parent d15436458f
commit cd4147423c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 23 additions and 39 deletions

View file

@ -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")

View file

@ -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()));
}

View file

@ -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
|