diff --git a/crates/ruff_python_formatter/src/expression/expr_lambda.rs b/crates/ruff_python_formatter/src/expression/expr_lambda.rs index c7d9a66aee..34bfdd8a01 100644 --- a/crates/ruff_python_formatter/src/expression/expr_lambda.rs +++ b/crates/ruff_python_formatter/src/expression/expr_lambda.rs @@ -94,8 +94,9 @@ impl FormatNodeRule for FormatExprLambda { format_args![token("("), block_indent(&body), token(")")] ] .fmt(f) - } else if has_own_parentheses(body, f.context()).is_some() { - // We probably need to be more careful here and preserve parentheses if there are comments? + } else if has_own_parentheses(body, f.context()).is_some() + || comments.contains_comments(body.as_ref().into()) + { body.format().fmt(f) } else { parenthesize_if_expands(&body.format().with_options(Parentheses::Never)).fmt(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 ec91dd0e1a..0ddf677b8b 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 @@ -913,27 +913,7 @@ if 1: ): pass -@@ -156,7 +138,8 @@ - *x: x - ) - --lambda: ( # comment -+lambda: ( -+ # comment - x - ) - -@@ -184,7 +167,8 @@ - - ( - lambda: # comment -- ( # comment -+ ( -+ # comment - x - ) - ) -@@ -218,71 +202,79 @@ +@@ -218,71 +200,79 @@ # Leading lambda x: ( @@ -1072,7 +1052,7 @@ if 1: # Regression tests for https://github.com/astral-sh/ruff/issues/8179 -@@ -291,9 +283,9 @@ +@@ -291,9 +281,9 @@ c, d, e, @@ -1085,7 +1065,7 @@ if 1: ) -@@ -302,15 +294,9 @@ +@@ -302,15 +292,9 @@ c, d, e, @@ -1104,7 +1084,7 @@ if 1: g=10, ) -@@ -320,9 +306,9 @@ +@@ -320,9 +304,9 @@ c, d, e, @@ -1117,7 +1097,7 @@ if 1: ) -@@ -338,9 +324,9 @@ +@@ -338,9 +322,9 @@ class C: function_dict: Dict[Text, Callable[[CRFToken], Any]] = { @@ -1130,7 +1110,7 @@ if 1: } -@@ -352,42 +338,40 @@ +@@ -352,42 +336,40 @@ def foo(): if True: if True: @@ -1189,7 +1169,7 @@ if 1: CREATE TABLE {table} AS SELECT ROW_NUMBER() OVER () AS id, {var} FROM ( -@@ -408,12 +392,12 @@ +@@ -408,12 +390,12 @@ # 6 ) @@ -1206,7 +1186,7 @@ if 1: ) very_long_variable_name_x, very_long_variable_name_y = ( -@@ -421,8 +405,8 @@ +@@ -421,8 +403,8 @@ lambda b: b * another_very_long_expression_here, )