diff --git a/crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/lambda.py b/crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/lambda.py index 7a55c8aa27..444b23a94d 100644 --- a/crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/lambda.py +++ b/crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/lambda.py @@ -725,3 +725,25 @@ transform = lambda left, right: ibis.timestamp("2017-04-01").cast(dt.date).betwe x: x ) + +( + lambda + # comment + *x, + **y: x +) + +( + lambda + * # comment 2 + x, + **y: + x +) + +( + lambda + ** # comment 1 + x: + x +) diff --git a/crates/ruff_python_formatter/src/other/parameters.rs b/crates/ruff_python_formatter/src/other/parameters.rs index 1c6682bab1..2e12f48456 100644 --- a/crates/ruff_python_formatter/src/other/parameters.rs +++ b/crates/ruff_python_formatter/src/other/parameters.rs @@ -241,6 +241,32 @@ impl FormatNodeRule for FormatParameters { let num_parameters = item.len(); if self.parentheses == ParametersParentheses::Never { + // In a lambda, format any leading comments on the first parameter outside of the + // parameters group so that the parameters don't break. For example, format this input: + // + // ```py + // ( + // lambda + // * # this becomes a leading comment on *x + // x, **y: + // x + // ) + // ``` + // + // as: + // + // ```py + // ( + // lambda + // # this becomes a leading comment on *x + // *x, **y: x + // ) + // ``` + if let Some(first) = item.iter().next() + && comments.has_leading(first.as_parameter()) + { + leading_node_comments(first.as_parameter()).fmt(f)?; + } write!(f, [group(&format_inner), dangling_comments(dangling)]) } else if num_parameters == 0 { let mut f = WithNodeLevel::new(NodeLevel::ParenthesizedExpression, f); diff --git a/crates/ruff_python_formatter/tests/snapshots/format@expression__lambda.py.snap b/crates/ruff_python_formatter/tests/snapshots/format@expression__lambda.py.snap index 7cd8e61b2b..18f9eae9ef 100644 --- a/crates/ruff_python_formatter/tests/snapshots/format@expression__lambda.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/format@expression__lambda.py.snap @@ -731,6 +731,28 @@ transform = lambda left, right: ibis.timestamp("2017-04-01").cast(dt.date).betwe x: x ) + +( + lambda + # comment + *x, + **y: x +) + +( + lambda + * # comment 2 + x, + **y: + x +) + +( + lambda + ** # comment 1 + x: + x +) ``` ## Output @@ -1495,6 +1517,24 @@ transform = ( y, *x: # comment 2 x ) + +( + lambda + # comment + *x, **y: x +) + +( + lambda + # comment 2 + *x, **y: x +) + +( + lambda + # comment 1 + **x: x +) ```