mirror of https://github.com/astral-sh/ruff
## Summary This PR makes two changes to our formatting of `lambda` expressions: 1. We now parenthesize the body expression if it expands 2. We now try to keep the parameters on a single line The latter of these fixes #8179: Black formatting and this PR's formatting: ```py def a(): return b( c, d, e, f=lambda self, *args, **kwargs: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa( *args, **kwargs ), ) ``` Stable Ruff formatting ```py def a(): return b( c, d, e, f=lambda self, *args, **kwargs: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(*args, **kwargs), ) ``` We don't parenthesize the body expression here because the call to `aaaa...` has its own parentheses, but adding a binary operator shows the new parenthesization: ```diff @@ -3,7 +3,7 @@ c, d, e, - f=lambda self, *args, **kwargs: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa( - *args, **kwargs - ) + 1, + f=lambda self, *args, **kwargs: ( + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(*args, **kwargs) + 1 + ), ) ``` This is actually a new divergence from Black, which formats this input like this: ```py def a(): return b( c, d, e, f=lambda self, *args, **kwargs: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa( *args, **kwargs ) + 1, ) ``` But I think this is an improvement, unlike the case from #8179. One other, smaller benefit is that because we now add parentheses to lambda bodies, we also remove redundant parentheses: ```diff @pytest.mark.parametrize( "f", [ - lambda x: (x.expanding(min_periods=5).cov(x, pairwise=True)), - lambda x: (x.expanding(min_periods=5).corr(x, pairwise=True)), + lambda x: x.expanding(min_periods=5).cov(x, pairwise=True), + lambda x: x.expanding(min_periods=5).corr(x, pairwise=True), ], ) def test_moment_functions_zero_length_pairwise(f): ``` ## Test Plan New tests taken from #8465 and probably a few more I should grab from the ecosystem results. --------- Co-authored-by: Micha Reiser <micha@reiser.io> |
||
|---|---|---|
| .. | ||
| binary_like.rs | ||
| expr_attribute.rs | ||
| expr_await.rs | ||
| expr_bin_op.rs | ||
| expr_bool_op.rs | ||
| expr_boolean_literal.rs | ||
| expr_bytes_literal.rs | ||
| expr_call.rs | ||
| expr_compare.rs | ||
| expr_dict.rs | ||
| expr_dict_comp.rs | ||
| expr_ellipsis_literal.rs | ||
| expr_f_string.rs | ||
| expr_generator.rs | ||
| expr_if.rs | ||
| expr_ipy_escape_command.rs | ||
| expr_lambda.rs | ||
| expr_list.rs | ||
| expr_list_comp.rs | ||
| expr_name.rs | ||
| expr_named.rs | ||
| expr_none_literal.rs | ||
| expr_number_literal.rs | ||
| expr_set.rs | ||
| expr_set_comp.rs | ||
| expr_slice.rs | ||
| expr_starred.rs | ||
| expr_string_literal.rs | ||
| expr_subscript.rs | ||
| expr_t_string.rs | ||
| expr_tuple.rs | ||
| expr_unary_op.rs | ||
| expr_yield.rs | ||
| expr_yield_from.rs | ||
| mod.rs | ||
| operator.rs | ||
| parentheses.rs | ||