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 32a57bed4a..12e167d413 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 @@ -118,3 +118,38 @@ lambda a, /, c: a # 4 None # 5 ) + +( + lambda + # comment + *x: x +) + +( + lambda + # comment 1 + * + # comment 2 + x: + # comment 3 + x +) + +( + lambda # comment 1 + * # comment 2 + x: # comment 3 + x +) + +lambda *x\ + :x + +( + lambda + # comment + *\ + x: x +) + + diff --git a/crates/ruff_python_formatter/src/expression/expr_lambda.rs b/crates/ruff_python_formatter/src/expression/expr_lambda.rs index 54cd619b13..d2244596e0 100644 --- a/crates/ruff_python_formatter/src/expression/expr_lambda.rs +++ b/crates/ruff_python_formatter/src/expression/expr_lambda.rs @@ -43,6 +43,11 @@ impl FormatNodeRule for FormatExprLambda { write!(f, [dangling_comments(dangling)])?; } + // Insert hard line break if body has leading comment to ensure consistent formatting + if comments.has_leading(body.as_ref()) { + write!(f, [hard_line_break()])?; + } + write!(f, [body.format()]) } 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 73e3bcc04d..7585e7f371 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 @@ -124,6 +124,41 @@ lambda a, /, c: a # 4 None # 5 ) + +( + lambda + # comment + *x: x +) + +( + lambda + # comment 1 + * + # comment 2 + x: + # comment 3 + x +) + +( + lambda # comment 1 + * # comment 2 + x: # comment 3 + x +) + +lambda *x\ + :x + +( + lambda + # comment + *\ + x: x +) + + ``` ## Output @@ -185,7 +220,8 @@ lambda x: lambda y: lambda z: ( # Trailing a = ( - lambda: # Dangling + lambda: + # Dangling 1 ) @@ -232,22 +268,51 @@ lambda a, /, c: a # Dangling comments without parameters. ( - lambda: # 3 + lambda: + # 3 None ) ( - lambda: # 3 + lambda: + # 3 None ) ( - lambda: # 1 + lambda: + # 1 # 2 # 3 # 4 None # 5 ) + +( + lambda # comment + *x: x +) + +( + lambda # comment 1 + # comment 2 + *x: + # comment 3 + x +) + +( + lambda # comment 1 + # comment 2 + *x: x # comment 3 +) + +lambda *x: x + +( + lambda # comment + *x: x +) ```