working for Micha's exact example

This commit is contained in:
Brent Westbrook 2025-12-11 10:34:35 -05:00
parent 9d7d94c4f0
commit 2cb98d4cdb
No known key found for this signature in database
2 changed files with 46 additions and 14 deletions

View File

@ -1884,14 +1884,19 @@ fn handle_lambda_comment<'a>(
return CommentPlacement::dangling(comment.enclosing_node(), comment); return CommentPlacement::dangling(comment.enclosing_node(), comment);
} }
} else { } else {
// Comments between the lambda and the body are dangling on the lambda: // End-of-line comments between the lambda and the body are dangling on the lambda:
// ```python // ```python
// ( // (
// lambda: # comment // lambda: # comment
// y // y
// ) // )
// ``` // ```
// But own-line comments after `:` are leading on the body.
if comment.start() < lambda.body.start() { if comment.start() < lambda.body.start() {
if comment.line_position().is_own_line() {
return CommentPlacement::leading(&*lambda.body, comment);
}
// If the value is parenthesized, and the comment is within the parentheses, it should // If the value is parenthesized, and the comment is within the parentheses, it should
// be a leading comment on the value, not a dangling comment in the lambda, as in: // be a leading comment on the value, not a dangling comment in the lambda, as in:
// ```python // ```python

View File

@ -377,6 +377,32 @@ impl Format<PyFormatContext<'_>> for FormatBody<'_> {
); );
let fmt_body = format_with(|f: &mut PyFormatter| { let fmt_body = format_with(|f: &mut PyFormatter| {
let body_comments = f.context().comments().leading_dangling_trailing(&**body);
if body_comments.has_leading() {
if body_comments
.leading
.iter()
.any(|comment| comment.line_position().is_own_line())
{
write!(
f,
[
trailing_comments(dangling),
hard_line_break(),
body.format().with_options(Parentheses::Always),
]
)
} else {
write!(
f,
[
space(),
trailing_comments(dangling),
body.format().with_options(Parentheses::Always),
]
)
}
} else {
write!( write!(
f, f,
[ [
@ -390,6 +416,7 @@ impl Format<PyFormatContext<'_>> for FormatBody<'_> {
token(")") token(")")
] ]
) )
}
}); });
match layout { match layout {