diff --git a/README.md b/README.md index 1af19922e26fd..55886111321bf 100644 --- a/README.md +++ b/README.md @@ -957,6 +957,7 @@ For more, see [flake8-simplify](https://pypi.org/project/flake8-simplify/0.19.3/ | Code | Name | Message | Fix | | ---- | ---- | ------- | --- | +| SIM105 | UseContextlibSuppress | Use 'contextlib.suppress(..)' instead of try-except-pass | | | SIM118 | KeyInDict | Use `key in dict` instead of `key in dict.keys()` | 🛠 | | SIM222 | OrTrue | Use `True` instead of `... or True` | 🛠 | | SIM223 | AndFalse | Use `False` instead of `... and False` | 🛠 | diff --git a/resources/test/fixtures/flake8_simplify/SIM105.py b/resources/test/fixtures/flake8_simplify/SIM105.py new file mode 100644 index 0000000000000..e645a7ecdff0c --- /dev/null +++ b/resources/test/fixtures/flake8_simplify/SIM105.py @@ -0,0 +1,17 @@ +def foo(): + pass + +try: + foo() +except ValueError: + pass + +try: + foo() +except (ValueError, OSError): + pass + +try: + foo() +except: + pass diff --git a/ruff.schema.json b/ruff.schema.json index 1622898da7820..cd3152cf919ef 100644 --- a/ruff.schema.json +++ b/ruff.schema.json @@ -895,6 +895,8 @@ "S107", "SIM", "SIM1", + "SIM10", + "SIM105", "SIM11", "SIM118", "SIM2", diff --git a/src/checkers/ast.rs b/src/checkers/ast.rs index 900ec9bb15668..0ded63e19cb76 100644 --- a/src/checkers/ast.rs +++ b/src/checkers/ast.rs @@ -1272,6 +1272,9 @@ where .into_iter(), ); } + if self.settings.enabled.contains(&CheckCode::SIM105) { + flake8_simplify::plugins::use_contextlib_suppress(self, handlers); + } } StmtKind::Assign { targets, value, .. } => { if self.settings.enabled.contains(&CheckCode::E731) { diff --git a/src/flake8_simplify/mod.rs b/src/flake8_simplify/mod.rs index 92c3edb372711..e25d774c6452c 100644 --- a/src/flake8_simplify/mod.rs +++ b/src/flake8_simplify/mod.rs @@ -12,6 +12,7 @@ mod tests { use crate::registry::CheckCode; use crate::settings; + #[test_case(CheckCode::SIM105, Path::new("SIM105.py"); "SIM105")] #[test_case(CheckCode::SIM118, Path::new("SIM118.py"); "SIM118")] #[test_case(CheckCode::SIM222, Path::new("SIM222.py"); "SIM222")] #[test_case(CheckCode::SIM223, Path::new("SIM223.py"); "SIM223")] diff --git a/src/flake8_simplify/plugins/mod.rs b/src/flake8_simplify/plugins/mod.rs index cb786b1a7372a..afefd32289aa1 100644 --- a/src/flake8_simplify/plugins/mod.rs +++ b/src/flake8_simplify/plugins/mod.rs @@ -1,7 +1,9 @@ pub use bool_ops::{and_false, or_true}; pub use key_in_dict::{key_in_dict_compare, key_in_dict_for}; +pub use use_contextlib_suppress::use_contextlib_suppress; pub use yoda_conditions::yoda_conditions; mod bool_ops; mod key_in_dict; +mod use_contextlib_suppress; mod yoda_conditions; diff --git a/src/flake8_simplify/plugins/use_contextlib_suppress.rs b/src/flake8_simplify/plugins/use_contextlib_suppress.rs new file mode 100644 index 0000000000000..a5265aec6c328 --- /dev/null +++ b/src/flake8_simplify/plugins/use_contextlib_suppress.rs @@ -0,0 +1,42 @@ +use rustpython_ast::{Excepthandler, ExcepthandlerKind, ExprKind}; + +use crate::ast::helpers; +use crate::ast::types::Range; +use crate::checkers::ast::Checker; +use crate::registry::{Check, CheckKind}; + +pub fn use_contextlib_suppress(checker: &mut Checker, handlers: &[Excepthandler]) { + for handler in handlers { + let ExcepthandlerKind::ExceptHandler { type_, body, .. } = &handler.node; + if body.len() == 1 { + let node = &body[0].node; + if matches!(node, rustpython_ast::StmtKind::Pass) { + let exception = match type_ { + Some(type_) => match &type_.node { + ExprKind::Attribute { .. } | ExprKind::Name { .. } => { + let call_path = helpers::collect_call_paths(type_); + Some(call_path[0].to_string()) + } + ExprKind::Tuple { elts, .. } => { + let mut excs = Vec::new(); + for expr in elts { + let call_path = helpers::collect_call_paths(expr); + excs.extend(call_path); + } + Some(excs.join(", ")) + } + _ => None, + }, + None => None, + }; + let check = Check::new( + CheckKind::UseContextlibSuppress( + exception.unwrap_or_else(|| "Exception".to_string()), + ), + Range::from_located(handler), + ); + checker.add_check(check); + } + } + } +} diff --git a/src/flake8_simplify/snapshots/ruff__flake8_simplify__tests__SIM105_SIM105.py.snap b/src/flake8_simplify/snapshots/ruff__flake8_simplify__tests__SIM105_SIM105.py.snap new file mode 100644 index 0000000000000..9cfb721786650 --- /dev/null +++ b/src/flake8_simplify/snapshots/ruff__flake8_simplify__tests__SIM105_SIM105.py.snap @@ -0,0 +1,35 @@ +--- +source: src/flake8_simplify/mod.rs +expression: checks +--- +- kind: + UseContextlibSuppress: ValueError + location: + row: 6 + column: 0 + end_location: + row: 7 + column: 8 + fix: ~ + parent: ~ +- kind: + UseContextlibSuppress: "ValueError, OSError" + location: + row: 11 + column: 0 + end_location: + row: 12 + column: 8 + fix: ~ + parent: ~ +- kind: + UseContextlibSuppress: Exception + location: + row: 16 + column: 0 + end_location: + row: 17 + column: 8 + fix: ~ + parent: ~ + diff --git a/src/registry.rs b/src/registry.rs index 471287aed63b8..f187b8db8134c 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -217,6 +217,7 @@ pub enum CheckCode { YTT302, YTT303, // flake8-simplify + SIM105, SIM118, SIM222, SIM223, @@ -873,6 +874,7 @@ pub enum CheckKind { UnaryPrefixIncrement, UnreliableCallableCheck, UnusedLoopControlVariable(String), + UseContextlibSuppress(String), UselessComparison, UselessContextlibSuppress, UselessExpression, @@ -1371,6 +1373,7 @@ impl CheckCode { // flake8-blind-except CheckCode::BLE001 => CheckKind::BlindExcept("Exception".to_string()), // flake8-simplify + CheckCode::SIM105 => CheckKind::UseContextlibSuppress("..".to_string()), CheckCode::SIM118 => CheckKind::KeyInDict("key".to_string(), "dict".to_string()), CheckCode::SIM222 => CheckKind::OrTrue, CheckCode::SIM223 => CheckKind::AndFalse, @@ -1894,6 +1897,7 @@ impl CheckCode { CheckCode::S106 => CheckCategory::Flake8Bandit, CheckCode::S107 => CheckCategory::Flake8Bandit, // flake8-simplify + CheckCode::SIM105 => CheckCategory::Flake8Simplify, CheckCode::SIM118 => CheckCategory::Flake8Simplify, CheckCode::SIM222 => CheckCategory::Flake8Simplify, CheckCode::SIM223 => CheckCategory::Flake8Simplify, @@ -2142,6 +2146,7 @@ impl CheckKind { CheckKind::SysVersionCmpStr10 => &CheckCode::YTT302, CheckKind::SysVersionSlice1Referenced => &CheckCode::YTT303, // flake8-simplify + CheckKind::UseContextlibSuppress(..) => &CheckCode::SIM105, CheckKind::KeyInDict(..) => &CheckCode::SIM118, CheckKind::OrTrue => &CheckCode::SIM222, CheckKind::AndFalse => &CheckCode::SIM223, @@ -2652,6 +2657,9 @@ impl CheckKind { CheckKind::FStringDocstring => "f-string used as docstring. This will be interpreted \ by python as a joined string rather than a docstring." .to_string(), + CheckKind::UseContextlibSuppress(exception) => { + format!("Use 'contextlib.suppress({exception})' instead of try-except-pass") + } CheckKind::UselessContextlibSuppress => { "No arguments passed to `contextlib.suppress`. No exceptions will be suppressed \ and therefore this context manager is redundant" diff --git a/src/registry_gen.rs b/src/registry_gen.rs index cec25230ebf24..66ef90cf9a914 100644 --- a/src/registry_gen.rs +++ b/src/registry_gen.rs @@ -515,6 +515,8 @@ pub enum CheckCodePrefix { S107, SIM, SIM1, + SIM10, + SIM105, SIM11, SIM118, SIM2, @@ -798,6 +800,7 @@ impl CheckCodePrefix { CheckCode::YTT301, CheckCode::YTT302, CheckCode::YTT303, + CheckCode::SIM105, CheckCode::SIM118, CheckCode::SIM222, CheckCode::SIM223, @@ -2606,12 +2609,15 @@ impl CheckCodePrefix { CheckCodePrefix::S106 => vec![CheckCode::S106], CheckCodePrefix::S107 => vec![CheckCode::S107], CheckCodePrefix::SIM => vec![ + CheckCode::SIM105, CheckCode::SIM118, CheckCode::SIM222, CheckCode::SIM223, CheckCode::SIM300, ], - CheckCodePrefix::SIM1 => vec![CheckCode::SIM118], + CheckCodePrefix::SIM1 => vec![CheckCode::SIM105, CheckCode::SIM118], + CheckCodePrefix::SIM10 => vec![CheckCode::SIM105], + CheckCodePrefix::SIM105 => vec![CheckCode::SIM105], CheckCodePrefix::SIM11 => vec![CheckCode::SIM118], CheckCodePrefix::SIM118 => vec![CheckCode::SIM118], CheckCodePrefix::SIM2 => vec![CheckCode::SIM222, CheckCode::SIM223], @@ -3557,6 +3563,8 @@ impl CheckCodePrefix { CheckCodePrefix::S107 => SuffixLength::Three, CheckCodePrefix::SIM => SuffixLength::Zero, CheckCodePrefix::SIM1 => SuffixLength::One, + CheckCodePrefix::SIM10 => SuffixLength::Two, + CheckCodePrefix::SIM105 => SuffixLength::Three, CheckCodePrefix::SIM11 => SuffixLength::Two, CheckCodePrefix::SIM118 => SuffixLength::Three, CheckCodePrefix::SIM2 => SuffixLength::One,