From c0260719bc55e29c140237b8c6f361da3c50fe66 Mon Sep 17 00:00:00 2001 From: Jonathan Plasse <13716151+JonathanPlasse@users.noreply.github.com> Date: Tue, 28 Mar 2023 19:39:59 +0200 Subject: [PATCH] Exempt return with side effects for TRY300 --- crates/ruff/resources/test/fixtures/tryceratops/TRY300.py | 3 ++- .../ruff/src/rules/tryceratops/rules/try_consider_else.rs | 8 +++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/ruff/resources/test/fixtures/tryceratops/TRY300.py b/crates/ruff/resources/test/fixtures/tryceratops/TRY300.py index c45af4acb19fe1..e808302647168d 100644 --- a/crates/ruff/resources/test/fixtures/tryceratops/TRY300.py +++ b/crates/ruff/resources/test/fixtures/tryceratops/TRY300.py @@ -40,8 +40,9 @@ def noreturn(): logger.exception("process failed") -def still_good(): +def good_return_with_side_effects(): try: + pass return process() except MyException: logger.exception("process failed") diff --git a/crates/ruff/src/rules/tryceratops/rules/try_consider_else.rs b/crates/ruff/src/rules/tryceratops/rules/try_consider_else.rs index 35cd3275397037..fb50c685cf2c19 100644 --- a/crates/ruff/src/rules/tryceratops/rules/try_consider_else.rs +++ b/crates/ruff/src/rules/tryceratops/rules/try_consider_else.rs @@ -2,6 +2,7 @@ use rustpython_parser::ast::{Excepthandler, Stmt, StmtKind}; use ruff_diagnostics::{Diagnostic, Violation}; use ruff_macros::{derive_message_formats, violation}; +use ruff_python_ast::helpers::contains_effect; use ruff_python_ast::types::Range; use crate::checkers::ast::Checker; @@ -25,7 +26,12 @@ pub fn try_consider_else( ) { if body.len() > 1 && orelse.is_empty() && !handler.is_empty() { if let Some(stmt) = body.last() { - if let StmtKind::Return { .. } = &stmt.node { + if let StmtKind::Return { value } = &stmt.node { + if let Some(value) = value { + if contains_effect(&checker.ctx, value) { + return; + } + } checker .diagnostics .push(Diagnostic::new(TryConsiderElse, Range::from(stmt)));