diff --git a/resources/test/fixtures/flake8_simplify/SIM105.py b/resources/test/fixtures/flake8_simplify/SIM105.py index 178947b5f5..e6989c466b 100644 --- a/resources/test/fixtures/flake8_simplify/SIM105.py +++ b/resources/test/fixtures/flake8_simplify/SIM105.py @@ -41,3 +41,21 @@ except ValueError: 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 diff --git a/src/checkers/ast.rs b/src/checkers/ast.rs index 6cf3aa684c..572f8b62e9 100644 --- a/src/checkers/ast.rs +++ b/src/checkers/ast.rs @@ -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) { diff --git a/src/rules/flake8_simplify/rules/use_contextlib_suppress.rs b/src/rules/flake8_simplify/rules/use_contextlib_suppress.rs index 90e556f173..a9fe923380 100644 --- a/src/rules/flake8_simplify/rules/use_contextlib_suppress.rs +++ b/src/rules/flake8_simplify/rules/use_contextlib_suppress.rs @@ -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; @@ -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];