diff --git a/crates/ruff_python_formatter/src/comments/placement.rs b/crates/ruff_python_formatter/src/comments/placement.rs index 76449285be..7c00a1aec4 100644 --- a/crates/ruff_python_formatter/src/comments/placement.rs +++ b/crates/ruff_python_formatter/src/comments/placement.rs @@ -1884,14 +1884,19 @@ fn handle_lambda_comment<'a>( return CommentPlacement::dangling(comment.enclosing_node(), comment); } } 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 // ( // lambda: # comment // y // ) // ``` + // But own-line comments after `:` are leading on the body. 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 // be a leading comment on the value, not a dangling comment in the lambda, as in: // ```python diff --git a/crates/ruff_python_formatter/src/expression/expr_lambda.rs b/crates/ruff_python_formatter/src/expression/expr_lambda.rs index bf8e422401..7b9a4810db 100644 --- a/crates/ruff_python_formatter/src/expression/expr_lambda.rs +++ b/crates/ruff_python_formatter/src/expression/expr_lambda.rs @@ -377,19 +377,46 @@ impl Format> for FormatBody<'_> { ); let fmt_body = format_with(|f: &mut PyFormatter| { - write!( - f, - [ - space(), - token("("), - trailing_comments(after_parameters_end_of_line), - block_indent(&format_args!( - leading_comments(leading_body_comments), - body.format().with_options(Parentheses::Never) - )), - token(")") - ] - ) + 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!( + f, + [ + space(), + token("("), + trailing_comments(after_parameters_end_of_line), + block_indent(&format_args!( + leading_comments(leading_body_comments), + body.format().with_options(Parentheses::Never) + )), + token(")") + ] + ) + } }); match layout {