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

Restrict SIM105 to try blocks with a body of one simple statement #1948

Merged
merged 1 commit into from
Jan 18, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 18 additions & 0 deletions resources/test/fixtures/flake8_simplify/SIM105.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,21 @@ def foo():
pass
finally:
print('bar')

try:
foo()
foo()
except ValueError:
pass

try:
for i in range(3):
foo()
except ValueError:
pass

def bar():
try:
return foo()
except ValueError:
pass
2 changes: 1 addition & 1 deletion src/checkers/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1384,7 +1384,7 @@ where
}
if self.settings.rules.enabled(&RuleCode::SIM105) {
flake8_simplify::rules::use_contextlib_suppress(
self, stmt, handlers, orelse, finalbody,
self, stmt, body, handlers, orelse, finalbody,
);
}
if self.settings.rules.enabled(&RuleCode::SIM107) {
Expand Down
22 changes: 20 additions & 2 deletions src/rules/flake8_simplify/rules/use_contextlib_suppress.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use rustpython_ast::{Excepthandler, ExcepthandlerKind, Stmt, StmtKind};
use rustpython_ast::{Excepthandler, ExcepthandlerKind, Located, Stmt, StmtKind};

use crate::ast::helpers;
use crate::ast::types::Range;
Expand All @@ -10,11 +10,29 @@ use crate::violations;
pub fn use_contextlib_suppress(
checker: &mut Checker,
stmt: &Stmt,
body: &[Stmt],
handlers: &[Excepthandler],
orelse: &[Stmt],
finalbody: &[Stmt],
) {
if handlers.len() != 1 || !orelse.is_empty() || !finalbody.is_empty() {
if !matches!(
body,
[Located {
node: StmtKind::Delete { .. }
| StmtKind::Assign { .. }
| StmtKind::AugAssign { .. }
| StmtKind::AnnAssign { .. }
| StmtKind::Assert { .. }
| StmtKind::Import { .. }
| StmtKind::ImportFrom { .. }
| StmtKind::Expr { .. }
| StmtKind::Pass,
..
}]
) || handlers.len() != 1
|| !orelse.is_empty()
|| !finalbody.is_empty()
{
return;
}
let handler = &handlers[0];
Expand Down