Include else block in break detection (#1143)

This commit is contained in:
Charlie Marsh 2022-12-08 11:53:31 -05:00 committed by GitHub
parent a710e35ebc
commit c1b1ac069e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 4 deletions

View file

@ -75,7 +75,7 @@ def test_break_in_orelse_deep():
def test_break_in_orelse_deep2():
"""should rise a useless-else-on-loop message, as the break statement is only
"""should raise a useless-else-on-loop message, as the break statement is only
for the inner for loop
"""
for _ in range(10):
@ -101,3 +101,15 @@ def test_break_in_orelse_deep3():
else:
return True
return False
def test_break_in_if_orelse():
"""should raise a useless-else-on-loop message due to break in else"""
for _ in range(10):
if 1 < 2: # pylint: disable=comparison-of-constants
pass
else:
break
else:
return True
return False

View file

@ -7,7 +7,7 @@ use crate::Check;
fn loop_exits_early(body: &[Stmt]) -> bool {
body.iter().any(|stmt| match &stmt.node {
StmtKind::If { body, .. } => loop_exits_early(body),
StmtKind::If { body, orelse, .. } => loop_exits_early(body) || loop_exits_early(orelse),
StmtKind::Try {
body,
handlers,
@ -16,11 +16,11 @@ fn loop_exits_early(body: &[Stmt]) -> bool {
..
} => {
loop_exits_early(body)
|| loop_exits_early(orelse)
|| loop_exits_early(finalbody)
|| handlers.iter().any(|handler| match &handler.node {
ExcepthandlerKind::ExceptHandler { body, .. } => loop_exits_early(body),
})
|| loop_exits_early(orelse)
|| loop_exits_early(finalbody)
}
StmtKind::For { orelse, .. }
| StmtKind::AsyncFor { orelse, .. }