flake8-simplify: avoid unnecessary builtins import for SIM105 (#22358)

This commit is contained in:
Jason K Hall
2026-01-05 02:58:46 -07:00
committed by GitHub
parent 3d3af6f7c8
commit 24580e2ee8
2 changed files with 15 additions and 19 deletions

View File

@@ -157,14 +157,11 @@ pub(crate) fn suppressible_exception(
let mut rest: Vec<Edit> = Vec::new();
let content: String;
if exception == "BaseException" && handler_names.is_empty() {
let (import_exception, binding_exception) =
checker.importer().get_or_import_symbol(
&ImportRequest::import("builtins", &exception),
stmt.start(),
checker.semantic(),
)?;
let (import_exception, binding_exception) = checker
.importer()
.get_or_import_builtin_symbol(&exception, stmt.start(), checker.semantic())?;
content = format!("with {binding}({binding_exception})");
rest.push(import_exception);
rest.extend(import_exception);
} else {
content = format!("with {binding}({exception})");
}

View File

@@ -104,22 +104,21 @@ SIM105 [*] Use `contextlib.suppress(BaseException)` instead of `try`-`except`-`p
|
help: Replace `try`-`except`-`pass` with `with contextlib.suppress(BaseException): ...`
1 + import contextlib
2 + import builtins
3 | def foo():
4 | pass
5 |
2 | def foo():
3 | pass
4 |
--------------------------------------------------------------------------------
24 | pass
25 |
26 | # SIM105
23 | pass
24 |
25 | # SIM105
- try:
27 + with contextlib.suppress(builtins.BaseException):
28 | foo()
26 + with contextlib.suppress(BaseException):
27 | foo()
- except:
- pass
29 |
30 | # SIM105
31 | try:
28 |
29 | # SIM105
30 | try:
note: This is an unsafe fix and may change runtime behavior
SIM105 [*] Use `contextlib.suppress(a.Error, b.Error)` instead of `try`-`except`-`pass`