Avoid useless-else-on-loop for break within match (#3136)

This commit is contained in:
Charlie Marsh 2023-02-22 14:12:44 -05:00 committed by GitHub
parent 6ced5122e4
commit 4ad4e3e091
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 15 additions and 1 deletions

View file

@ -124,3 +124,14 @@ def test_break_in_with():
else:
return True
return False
def test_break_in_match():
"""no false positive for break in match"""
for name in ["demo"]:
match name:
case "demo":
break
else:
return True
return False

View file

@ -1,5 +1,5 @@
use ruff_macros::{define_violation, derive_message_formats};
use rustpython_parser::ast::{ExcepthandlerKind, Stmt, StmtKind};
use rustpython_parser::ast::{ExcepthandlerKind, MatchCase, Stmt, StmtKind};
use crate::ast::helpers;
use crate::checkers::ast::Checker;
@ -23,6 +23,9 @@ fn loop_exits_early(body: &[Stmt]) -> bool {
body.iter().any(|stmt| match &stmt.node {
StmtKind::If { body, orelse, .. } => loop_exits_early(body) || loop_exits_early(orelse),
StmtKind::With { body, .. } | StmtKind::AsyncWith { body, .. } => loop_exits_early(body),
StmtKind::Match { cases, .. } => cases
.iter()
.any(|MatchCase { body, .. }| loop_exits_early(body)),
StmtKind::Try {
body,
handlers,