From c1b1ac069ee5ead3a43cb4b4f142ac8e339ee18e Mon Sep 17 00:00:00 2001 From: Charlie Marsh Date: Thu, 8 Dec 2022 11:53:31 -0500 Subject: [PATCH] Include else block in break detection (#1143) --- .../test/fixtures/pylint/useless_else_on_loop.py | 14 +++++++++++++- src/pylint/plugins/useless_else_on_loop.rs | 6 +++--- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/resources/test/fixtures/pylint/useless_else_on_loop.py b/resources/test/fixtures/pylint/useless_else_on_loop.py index 9d370dc12f..5881a160c2 100644 --- a/resources/test/fixtures/pylint/useless_else_on_loop.py +++ b/resources/test/fixtures/pylint/useless_else_on_loop.py @@ -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 diff --git a/src/pylint/plugins/useless_else_on_loop.rs b/src/pylint/plugins/useless_else_on_loop.rs index 444f978c96..763052856c 100644 --- a/src/pylint/plugins/useless_else_on_loop.rs +++ b/src/pylint/plugins/useless_else_on_loop.rs @@ -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, .. }