From 0f0e7a521a44bd8424c3a6708d770ad1660f2907 Mon Sep 17 00:00:00 2001 From: Charlie Marsh Date: Sun, 19 Feb 2023 11:17:04 -0500 Subject: [PATCH] Avoid false-positives for break in with (#3032) --- .../test/fixtures/pylint/useless_else_on_loop.py | 11 +++++++++++ .../src/rules/pylint/rules/useless_else_on_loop.rs | 1 + 2 files changed, 12 insertions(+) diff --git a/crates/ruff/resources/test/fixtures/pylint/useless_else_on_loop.py b/crates/ruff/resources/test/fixtures/pylint/useless_else_on_loop.py index 5881a160c2f29..6333c7d2d545c 100644 --- a/crates/ruff/resources/test/fixtures/pylint/useless_else_on_loop.py +++ b/crates/ruff/resources/test/fixtures/pylint/useless_else_on_loop.py @@ -113,3 +113,14 @@ def test_break_in_if_orelse(): else: return True return False + + +def test_break_in_with(): + """no false positive for break in with""" + for name in ["demo"]: + with open(__file__) as f: + if name in f.read(): + break + else: + return True + return False diff --git a/crates/ruff/src/rules/pylint/rules/useless_else_on_loop.rs b/crates/ruff/src/rules/pylint/rules/useless_else_on_loop.rs index 108d53e14aad5..c650de473a843 100644 --- a/crates/ruff/src/rules/pylint/rules/useless_else_on_loop.rs +++ b/crates/ruff/src/rules/pylint/rules/useless_else_on_loop.rs @@ -22,6 +22,7 @@ impl Violation for UselessElseOnLoop { 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::Try { body, handlers,