Extend SIM105 to match also 'Ellipsis only' bodies in exception handlers (#3925)

This commit is contained in:
Leiser Fernández Gallo 2023-04-10 15:55:02 +02:00 committed by GitHub
parent 002caadf9e
commit 333f1bd9ce
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 61 additions and 2 deletions

View File

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

View File

@ -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<String> = helpers::extract_handled_exceptions(handlers)
.into_iter()
.filter_map(compose_call_path)

View File

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