diff --git a/crates/ruff/resources/test/fixtures/flake8_simplify/SIM105.py b/crates/ruff/resources/test/fixtures/flake8_simplify/SIM105.py index e6989c466b..d54cf3f9c7 100644 --- a/crates/ruff/resources/test/fixtures/flake8_simplify/SIM105.py +++ b/crates/ruff/resources/test/fixtures/flake8_simplify/SIM105.py @@ -59,3 +59,15 @@ def bar(): return foo() except ValueError: pass + +def with_ellipsis(): + try: + foo() + except ValueError: + ... + +def with_ellipsis_and_return(): + try: + return foo() + except ValueError: + ... diff --git a/crates/ruff/src/rules/flake8_simplify/rules/suppressible_exception.rs b/crates/ruff/src/rules/flake8_simplify/rules/suppressible_exception.rs index c7a2df4b52..aceb8874e6 100644 --- a/crates/ruff/src/rules/flake8_simplify/rules/suppressible_exception.rs +++ b/crates/ruff/src/rules/flake8_simplify/rules/suppressible_exception.rs @@ -1,4 +1,6 @@ -use rustpython_parser::ast::{Excepthandler, ExcepthandlerKind, Located, Location, Stmt, StmtKind}; +use rustpython_parser::ast::{ + Constant, Excepthandler, ExcepthandlerKind, ExprKind, Located, Location, Stmt, StmtKind, +}; use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix}; use ruff_macros::{derive_message_formats, violation}; @@ -60,7 +62,17 @@ pub fn suppressible_exception( let handler = &handlers[0]; let ExcepthandlerKind::ExceptHandler { body, .. } = &handler.node; if body.len() == 1 { - if matches!(body[0].node, StmtKind::Pass) { + let node = &body[0].node; + if matches!(node, StmtKind::Pass) + || (matches!( + node, + StmtKind::Expr { + value, + .. + } + if matches!(**value, Located { node: ExprKind::Constant { value: Constant::Ellipsis, .. }, ..}) + )) + { let handler_names: Vec = helpers::extract_handled_exceptions(handlers) .into_iter() .filter_map(compose_call_path) diff --git a/crates/ruff/src/rules/flake8_simplify/snapshots/ruff__rules__flake8_simplify__tests__SIM105_SIM105.py.snap b/crates/ruff/src/rules/flake8_simplify/snapshots/ruff__rules__flake8_simplify__tests__SIM105_SIM105.py.snap index f28d9e8688..8ba5fd9a11 100644 --- a/crates/ruff/src/rules/flake8_simplify/snapshots/ruff__rules__flake8_simplify__tests__SIM105_SIM105.py.snap +++ b/crates/ruff/src/rules/flake8_simplify/snapshots/ruff__rules__flake8_simplify__tests__SIM105_SIM105.py.snap @@ -142,4 +142,39 @@ expression: diagnostics row: 22 column: 8 parent: ~ +- kind: + name: SuppressibleException + body: "Use `contextlib.suppress(ValueError)` instead of `try`-`except`-`pass`" + suggestion: "Replace with `contextlib.suppress(ValueError)`" + fixable: true + location: + row: 64 + column: 4 + end_location: + row: 67 + column: 11 + fix: + edits: + - content: "import contextlib\n" + location: + row: 1 + column: 0 + end_location: + row: 1 + column: 0 + - content: with contextlib.suppress(ValueError) + location: + row: 64 + column: 4 + end_location: + row: 64 + column: 7 + - content: "" + location: + row: 66 + column: 0 + end_location: + row: 67 + column: 11 + parent: ~