Skip to content

Commit d75e6d2

Browse files
committed
[pylint] Fix PLR1708 false positives
1 parent a32d5b8 commit d75e6d2

File tree

2 files changed

+27
-9
lines changed

2 files changed

+27
-9
lines changed

crates/ruff_linter/resources/test/fixtures/pylint/stop_iteration_return.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,3 +129,15 @@ def generator_with_lambda():
129129
yield 1
130130
func = lambda x: x # Just a regular lambda
131131
yield 2
132+
133+
# See: https://github.com/astral-sh/ruff/issues/21162
134+
def f():
135+
def g():
136+
yield 1
137+
raise StopIteration
138+
139+
140+
def g():
141+
def f():
142+
raise StopIteration
143+
yield 1

crates/ruff_linter/src/rules/pylint/rules/stop_iteration_return.rs

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
use ruff_macros::{ViolationMetadata, derive_message_formats};
2-
use ruff_python_ast as ast;
3-
use ruff_python_ast::visitor::{Visitor, walk_expr, walk_stmt};
2+
use ruff_python_ast::{
3+
self as ast,
4+
visitor::{Visitor, walk_expr, walk_stmt},
5+
};
6+
use ruff_python_semantic::ScopeKind;
47
use ruff_text_size::Ranged;
58

69
use crate::Violation;
@@ -77,12 +80,8 @@ pub(crate) fn stop_iteration_return(checker: &Checker, raise_stmt: &ast::StmtRai
7780

7881
/// Returns true if we're inside a function that contains any `yield`/`yield from`.
7982
fn in_generator_context(checker: &Checker) -> bool {
80-
for scope in checker.semantic().current_scopes() {
81-
if let ruff_python_semantic::ScopeKind::Function(function_def) = scope.kind {
82-
if contains_yield_statement(&function_def.body) {
83-
return true;
84-
}
85-
}
83+
if let ScopeKind::Function(function_def) = checker.semantic().current_scope().kind {
84+
return contains_yield_statement(&function_def.body);
8685
}
8786
false
8887
}
@@ -94,6 +93,13 @@ fn contains_yield_statement(body: &[ast::Stmt]) -> bool {
9493
}
9594

9695
impl Visitor<'_> for YieldFinder {
96+
fn visit_stmt(&mut self, stmt: &ast::Stmt) {
97+
match stmt {
98+
ast::Stmt::FunctionDef(_) | ast::Stmt::ClassDef(_) => {}
99+
_ => walk_stmt(self, stmt),
100+
}
101+
}
102+
97103
fn visit_expr(&mut self, expr: &ast::Expr) {
98104
if matches!(expr, ast::Expr::Yield(_) | ast::Expr::YieldFrom(_)) {
99105
self.found = true;
@@ -105,7 +111,7 @@ fn contains_yield_statement(body: &[ast::Stmt]) -> bool {
105111

106112
let mut finder = YieldFinder { found: false };
107113
for stmt in body {
108-
walk_stmt(&mut finder, stmt);
114+
finder.visit_stmt(stmt);
109115
if finder.found {
110116
return true;
111117
}

0 commit comments

Comments
 (0)