-
Notifications
You must be signed in to change notification settings - Fork 1.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[flake8-bugbear
] Implement return-in-generator
(B901
)
#11644
Merged
charliermarsh
merged 7 commits into
astral-sh:main
from
tobb10001:b901-return-x-generator-function
May 31, 2024
Merged
Changes from 1 commit
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
9d5a280
implement bugbear B901
tobb10001 fd065ce
B901: use `if let` instead of `Option::is_some()`
tobb10001 4d71781
B901: avoid additional is_expr_stmt variable
tobb10001 ddbf0b0
Merge branch 'main' into b901-return-x-generator-function
charliermarsh 9065fe5
Format fixture
charliermarsh f19809c
Rename to return-in-generator
charliermarsh 253e157
Tweak documentation
charliermarsh File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
77 changes: 77 additions & 0 deletions
77
crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B901.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
""" | ||
Should emit: | ||
B901 - on lines 9, 36 | ||
""" | ||
|
||
def broken(): | ||
if True: | ||
return [1, 2, 3] | ||
|
||
yield 3 | ||
yield 2 | ||
yield 1 | ||
|
||
|
||
def not_broken(): | ||
if True: | ||
return | ||
|
||
yield 3 | ||
yield 2 | ||
yield 1 | ||
|
||
|
||
def not_broken2(): | ||
return not_broken() | ||
|
||
|
||
def not_broken3(): | ||
return | ||
|
||
yield from not_broken() | ||
|
||
|
||
def broken2(): | ||
return [3, 2, 1] | ||
|
||
yield from not_broken() | ||
|
||
|
||
async def not_broken4(): | ||
import asyncio | ||
|
||
await asyncio.sleep(1) | ||
return 1 | ||
|
||
|
||
def not_broken5(): | ||
def inner(): | ||
return 2 | ||
|
||
yield inner() | ||
|
||
|
||
def not_broken6(): | ||
return (yield from []) | ||
|
||
|
||
def not_broken7(): | ||
x = yield from [] | ||
return x | ||
|
||
|
||
def not_broken8(): | ||
x = None | ||
|
||
def inner(ex): | ||
nonlocal x | ||
x = ex | ||
|
||
inner((yield from [])) | ||
return x | ||
|
||
|
||
class NotBroken9(object): | ||
def __await__(self): | ||
yield from function() | ||
return 42 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
97 changes: 97 additions & 0 deletions
97
crates/ruff_linter/src/rules/flake8_bugbear/rules/return_x_in_generator.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,97 @@ | ||
use ruff_diagnostics::Diagnostic; | ||
use ruff_diagnostics::Violation; | ||
use ruff_macros::{derive_message_formats, violation}; | ||
use ruff_python_ast::visitor; | ||
use ruff_python_ast::visitor::Visitor; | ||
use ruff_python_ast::{self as ast, Expr, Stmt, StmtFunctionDef}; | ||
use ruff_text_size::TextRange; | ||
|
||
use crate::checkers::ast::Checker; | ||
|
||
/// ## What it does | ||
/// Checks for `return x` statements in functions, that also contain yield | ||
/// statements. | ||
/// | ||
/// ## Why is this bad? | ||
/// Using `return x` in a generator function used to be syntactically invalid | ||
/// in Python 2. In Python 3 `return x` can be used in a generator as a return | ||
/// value in conjunction with yield from. Users coming from Python 2 may expect | ||
/// the old behavior which might lead to bugs. Use native async def coroutines | ||
/// or mark intentional return x usage with # noqa on the same line. | ||
/// | ||
/// ## Example | ||
/// ```python | ||
/// def broken(): | ||
/// if True: | ||
/// return [1, 2, 3] | ||
/// | ||
/// yield 3 | ||
/// yield 2 | ||
/// yield 1 | ||
/// ``` | ||
#[violation] | ||
pub struct ReturnXInGenerator; | ||
|
||
impl Violation for ReturnXInGenerator { | ||
#[derive_message_formats] | ||
fn message(&self) -> String { | ||
format!("Using `yield` together with `return x`. Use native `async def` coroutines or put a `# noqa` comment on this line if this was intentional.") | ||
} | ||
} | ||
|
||
#[derive(Default)] | ||
struct ReturnXInGeneratorVisitor { | ||
return_: Option<TextRange>, | ||
has_yield: bool, | ||
|
||
in_expr_statement: bool, | ||
} | ||
|
||
impl Visitor<'_> for ReturnXInGeneratorVisitor { | ||
fn visit_stmt(&mut self, stmt: &Stmt) { | ||
match stmt { | ||
Stmt::FunctionDef(_) => { | ||
// do not recurse into nested functions, as they are evaluated | ||
// individually | ||
} | ||
Stmt::Return(ast::StmtReturn { value, range }) => { | ||
if Option::is_some(value) { | ||
self.return_ = Some(*range); | ||
} | ||
} | ||
_ => { | ||
self.in_expr_statement = stmt.is_expr_stmt(); | ||
visitor::walk_stmt(self, stmt); | ||
} | ||
} | ||
} | ||
|
||
fn visit_expr(&mut self, expr: &Expr) { | ||
if !self.in_expr_statement { | ||
return; | ||
} | ||
match expr { | ||
Expr::Yield(_) | Expr::YieldFrom(_) => { | ||
self.has_yield = true; | ||
} | ||
_ => {} | ||
} | ||
} | ||
} | ||
|
||
/// B901 | ||
pub(crate) fn return_x_in_generator(checker: &mut Checker, function_def: &StmtFunctionDef) { | ||
if function_def.name.id == "__await__" { | ||
return; | ||
} | ||
|
||
let mut visitor = ReturnXInGeneratorVisitor::default(); | ||
visitor.visit_body(&function_def.body); | ||
|
||
if Option::is_some(&visitor.return_) && visitor.has_yield { | ||
tobb10001 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
checker.diagnostics.push(Diagnostic::new( | ||
ReturnXInGenerator, | ||
visitor.return_.unwrap(), | ||
)); | ||
} | ||
} |
21 changes: 21 additions & 0 deletions
21
...les/flake8_bugbear/snapshots/ruff_linter__rules__flake8_bugbear__tests__B901_B901.py.snap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
--- | ||
source: crates/ruff_linter/src/rules/flake8_bugbear/mod.rs | ||
--- | ||
B901.py:8:9: B901 Using `yield` together with `return x`. Use native `async def` coroutines or put a `# noqa` comment on this line if this was intentional. | ||
| | ||
6 | def broken(): | ||
7 | if True: | ||
8 | return [1, 2, 3] | ||
| ^^^^^^^^^^^^^^^^ B901 | ||
9 | | ||
10 | yield 3 | ||
| | ||
|
||
B901.py:35:5: B901 Using `yield` together with `return x`. Use native `async def` coroutines or put a `# noqa` comment on this line if this was intentional. | ||
| | ||
34 | def broken2(): | ||
35 | return [3, 2, 1] | ||
| ^^^^^^^^^^^^^^^^ B901 | ||
36 | | ||
37 | yield from not_broken() | ||
| |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think I would do this by checking
Stmt::Expr
here, and then just introspecting the value directly to see if the value isExpr::Yield
.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good idea, I updated the implementation to this.