@@ -4,7 +4,8 @@ use ruff_python_ast::ExprLambda;
44use ruff_text_size:: Ranged ;
55
66use crate :: comments:: { dangling_comments, SourceComment } ;
7- use crate :: expression:: parentheses:: { NeedsParentheses , OptionalParentheses } ;
7+ use crate :: expression:: parentheses:: { NeedsParentheses , OptionalParentheses , Parenthesize } ;
8+ use crate :: expression:: { has_own_parentheses, maybe_parenthesize_expression} ;
89use crate :: other:: parameters:: ParametersParentheses ;
910use crate :: prelude:: * ;
1011
@@ -25,7 +26,7 @@ impl FormatNodeRule<ExprLambda> for FormatExprLambda {
2526 write ! ( f, [ token( "lambda" ) ] ) ?;
2627
2728 if let Some ( parameters) = parameters {
28- // In this context, a dangling comment can either be a comment between the `lambda` the
29+ // In this context, a dangling comment can either be a comment between the `lambda` and the
2930 // parameters, or a comment between the parameters and the body.
3031 let ( dangling_before_parameters, dangling_after_parameters) = dangling
3132 . split_at ( dangling. partition_point ( |comment| comment. end ( ) < parameters. start ( ) ) ) ;
@@ -36,20 +37,30 @@ impl FormatNodeRule<ExprLambda> for FormatExprLambda {
3637 write ! ( f, [ dangling_comments( dangling_before_parameters) ] ) ?;
3738 }
3839
39- write ! (
40- f,
41- [ parameters
42- . format( )
43- . with_options( ParametersParentheses :: Never ) ]
44- ) ?;
40+ group ( & format_with ( |f : & mut PyFormatter | {
41+ if f. context ( ) . node_level ( ) . is_parenthesized ( ) {
42+ soft_block_indent (
43+ & parameters
44+ . format ( )
45+ . with_options ( ParametersParentheses :: Never ) ,
46+ )
47+ . fmt ( f)
48+ } else {
49+ parameters
50+ . format ( )
51+ . with_options ( ParametersParentheses :: Never )
52+ . fmt ( f)
53+ } ?;
4554
46- write ! ( f , [ token( ":" ) ] ) ?;
55+ token ( ":" ) . fmt ( f ) ?;
4756
48- if dangling_after_parameters. is_empty ( ) {
49- write ! ( f, [ space( ) ] ) ?;
50- } else {
51- write ! ( f, [ dangling_comments( dangling_after_parameters) ] ) ?;
52- }
57+ if dangling_after_parameters. is_empty ( ) {
58+ space ( ) . fmt ( f)
59+ } else {
60+ dangling_comments ( dangling_after_parameters) . fmt ( f)
61+ }
62+ } ) )
63+ . fmt ( f) ?;
5364 } else {
5465 write ! ( f, [ token( ":" ) ] ) ?;
5566
@@ -61,7 +72,12 @@ impl FormatNodeRule<ExprLambda> for FormatExprLambda {
6172 }
6273 }
6374
64- write ! ( f, [ body. format( ) ] )
75+ // Avoid parenthesizing lists, dictionaries, etc.
76+ if f. context ( ) . is_stable ( ) || has_own_parentheses ( body, f. context ( ) ) . is_some ( ) {
77+ body. format ( ) . fmt ( f)
78+ } else {
79+ maybe_parenthesize_expression ( body, item, Parenthesize :: IfBreaksOrIfRequired ) . fmt ( f)
80+ }
6581 }
6682
6783 fn fmt_dangling_comments (
0 commit comments