MCPcopy Create free account
hub / github.com/astral-sh/ruff / fmt

Method fmt

crates/ruff_python_formatter/src/expression/expr_lambda.rs:261–471  ·  view source on GitHub ↗
(&self, f: &mut PyFormatter)

Source from the content-addressed store, hash-verified

259impl Format<PyFormatContext<'_>> for FormatBody<'_> {
260 #[expect(clippy::if_same_then_else)]
261 fn fmt(&self, f: &mut PyFormatter) -> FormatResult<()> {
262 let FormatBody {
263 dangling_header_comments,
264 body,
265 needs_parentheses,
266 } = self;
267
268 let body = *body;
269 let comments = f.context().comments().clone();
270 let body_comments = comments.leading_dangling_trailing(body);
271
272 if !dangling_header_comments.is_empty() {
273 // Split the dangling header comments into trailing comments formatted with the lambda
274 // header (1) and leading comments formatted with the body (2, 3, 4).
275 //
276 // ```python
277 // (
278 // lambda # 1
279 // # 2
280 // : # 3
281 // # 4
282 // y
283 // )
284 // ```
285 //
286 // Note that these are split based on their line position rather than using
287 // `partition_point` based on a range, for example.
288 let (trailing_header_comments, leading_body_comments) = dangling_header_comments
289 .split_at(
290 dangling_header_comments
291 .iter()
292 .position(|comment| comment.line_position().is_own_line())
293 .unwrap_or(dangling_header_comments.len()),
294 );
295
296 // If the body is parenthesized and has its own leading comments, preserve the
297 // separation between the dangling lambda comments and the body comments. For
298 // example, preserve this comment positioning:
299 //
300 // ```python
301 // (
302 // lambda: # 1
303 // # 2
304 // ( # 3
305 // x
306 // )
307 // )
308 // ```
309 //
310 // 1 and 2 are dangling on the lambda and emitted first, followed by a hard line
311 // break and the parenthesized body with its leading comments.
312 //
313 // However, when removing 2, 1 and 3 can instead be formatted on the same line:
314 //
315 // ```python
316 // (
317 // lambda: ( # 1 # 3
318 // x

Callers 1

fmt_fieldsMethod · 0.45

Calls 15

trailing_commentsFunction · 0.85
hard_line_breakFunction · 0.85
parenthesize_if_expandsFunction · 0.85
expand_parentFunction · 0.85
has_own_parenthesesFunction · 0.85
split_atMethod · 0.80
unwrap_orMethod · 0.80
has_leadingMethod · 0.80
has_trailing_own_lineMethod · 0.80
memoizedMethod · 0.80
spaceFunction · 0.50

Tested by

no test coverage detected