[RUF051] Ignore if else/elif block is present (#20705)

## Summary

Fixes #20700

`else` and `elif` blocks could previously be deleted when applying a fix
for this rule. If an `else` or `elif` branch is detected the rule will
not trigger. So now the rule will only flag if it is safe.
This commit is contained in:
Nikolas Hearp 2025-10-06 09:02:27 -04:00 committed by GitHub
parent 42b297bf44
commit 1c5666ce5d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 16 additions and 0 deletions

View file

@ -128,3 +128,15 @@ if f"0" in d: # f-string
if k in a.d: # Attribute dict
del a.d[k]
if k in d: # else statement
del d[k]
else:
pass
if k in d: # elif and else statements
del d[k]
elif 0 in d:
del d[0]
else:
pass

View file

@ -45,6 +45,10 @@ impl AlwaysFixableViolation for IfKeyInDictDel {
/// RUF051
pub(crate) fn if_key_in_dict_del(checker: &Checker, stmt: &StmtIf) {
if !stmt.elif_else_clauses.is_empty() {
return;
}
let [Stmt::Delete(delete)] = &stmt.body[..] else {
return;
};