Format ExprYield/ExprYieldFrom#5921
Format ExprYield/ExprYieldFrom#5921MichaReiser merged 13 commits intoastral-sh:mainfrom qdegraaf:feature/format-yield
ExprYield/ExprYieldFrom#5921Conversation
PR Check ResultsBenchmarkLinuxWindows |
|
The cpython check failed on def a():
with (yield):
passSeem like yield can appear everywhere, even in e.g. |
|
Interesting. I've expanded the test cases with a bunch more examples, and inverted the You mention |
| if parent.is_stmt_return() || parent.is_expr_await() { | ||
| OptionalParentheses::Always | ||
| } else { | ||
| if parent.is_stmt_assign() { |
There was a problem hiding this comment.
This should get a longer explanation about how only assignment right hand side and yield statements don't need parentheses and the special casing in the grammar, but we only need to handle assignment RHS here because StmtExpr doesn't add parentheses anyway (i just had to check that last part myself)
There was a problem hiding this comment.
Good point, added a comment describing the situation for both expr_yield and expr_yield_from. Thanks for the explanation in #5921 (comment) as well, helps me get a clearer image of how the formatter is structured and what to watch out for.
For def f():
yield 1you get (simplified for readability) impl FormatNodeRule<StmtExpr> for FormatStmtExpr {
fn fmt_fields(&self, item: &StmtExpr, f: &mut PyFormatter) -> FormatResult<()> {
let StmtExpr { value, .. } = item;
if is_arithmetic_like(value) {
maybe_parenthesize_expression(value, item, Parenthesize::Optional).fmt(f)
} else {
value.format().fmt(f)
}
}
}so this doesn't become def f():
(yield 1) |
MichaReiser
left a comment
There was a problem hiding this comment.
This is awesome. We may want to consider unifying the implementation in a follow up PR similar to AnyStmtWith (it could also implement NeedsParentheses so that we have all the logic in a single place).
ruff/crates/ruff_python_formatter/src/statement/stmt_with.rs
Lines 15 to 114 in 0301889
Good idea @MichaReiser. I'll finish up my outstanding PRs, then move to work on that. |
Summary
Formats:
yield xyield from xexpressions
Test Plan
Added fixtures for both expressions, ran black_comparison.
NOTE: This is my first formatter PR. From what I gather there are many many ways that interesting combinations of comments and parentheses can lead to unexpected results. I will try and run the formatter against some large codebases to see if any unexpected results pop up, but figured I'd open it for review in the meantime
Issue link:
Closes: #5916