[flake8-raise] Make fix unsafe if it deletes comments (RSE102) (#18788)

This commit is contained in:
chiri 2025-06-21 20:09:40 +03:00 committed by GitHub
parent cccbd0286e
commit da6cbeee60
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 41 additions and 6 deletions

View file

@ -105,3 +105,8 @@ if future.exception():
future = executor.submit(float, "a")
if future.exception():
raise future.Exception()
raise TypeError(
# comment
)

View file

@ -36,6 +36,10 @@ use crate::{AlwaysFixableViolation, Applicability, Edit, Fix};
/// raise TypeError
/// ```
///
/// ## Fix Safety
/// This rule's fix is marked as unsafe if removing the parentheses would also remove comments
/// or if its unclear whether the expression is a class or a function call.
///
/// ## References
/// - [Python documentation: The `raise` statement](https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement)
#[derive(ViolationMetadata)]
@ -133,13 +137,17 @@ pub(crate) fn unnecessary_paren_on_raise_exception(checker: &Checker, expr: &Exp
},
));
} else {
let applicability = if exception_type.is_some()
&& !checker.comment_ranges().intersects(arguments.range())
{
Applicability::Safe
} else {
Applicability::Unsafe
};
diagnostic.set_fix(Fix::applicable_edit(
Edit::range_deletion(arguments.range()),
if exception_type.is_some() {
Applicability::Safe
} else {
Applicability::Unsafe
},
applicability,
));
}
}

View file

@ -167,7 +167,7 @@ RSE102.py:37:16: RSE102 [*] Unnecessary parentheses on raised exception
|
= help: Remove unnecessary parentheses
Safe fix
Unsafe fix
34 34 | )
35 35 |
36 36 | # RSE102
@ -296,3 +296,25 @@ RSE102.py:107:27: RSE102 [*] Unnecessary parentheses on raised exception
106 106 | if future.exception():
107 |- raise future.Exception()
107 |+ raise future.Exception
108 108 |
109 109 |
110 110 | raise TypeError(
RSE102.py:110:16: RSE102 [*] Unnecessary parentheses on raised exception
|
110 | raise TypeError(
| ________________^
111 | | # comment
112 | | )
| |_^ RSE102
|
= help: Remove unnecessary parentheses
Unsafe fix
107 107 | raise future.Exception()
108 108 |
109 109 |
110 |-raise TypeError(
111 |- # comment
112 |-)
110 |+raise TypeError