diff --git a/crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/fstring.py b/crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/fstring.py index 2769203823..a60efa1cdd 100644 --- a/crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/fstring.py +++ b/crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/fstring.py @@ -24,3 +24,12 @@ result_f = ( r' \[Previous line repeated (\d+) more times\]' '\n' 'RecursionError: maximum recursion depth exceeded\n' ) + + +# Regression for fstring dropping comments that were accidentally attached to +# an expression inside a formatted value +( + f'{1}' + # comment + '' +) diff --git a/crates/ruff_python_formatter/src/comments/placement.rs b/crates/ruff_python_formatter/src/comments/placement.rs index 855930ba7c..a231a54096 100644 --- a/crates/ruff_python_formatter/src/comments/placement.rs +++ b/crates/ruff_python_formatter/src/comments/placement.rs @@ -80,6 +80,7 @@ pub(super) fn place_comment<'a>( CommentPlacement::Default(comment) } } + AnyNodeRef::ExprFString(fstring) => CommentPlacement::dangling(fstring, comment), AnyNodeRef::ExprList(_) | AnyNodeRef::ExprSet(_) | AnyNodeRef::ExprGeneratorExp(_) diff --git a/crates/ruff_python_formatter/tests/snapshots/format@expression__fstring.py.snap b/crates/ruff_python_formatter/tests/snapshots/format@expression__fstring.py.snap index 90a4b1e396..e6e7156208 100644 --- a/crates/ruff_python_formatter/tests/snapshots/format@expression__fstring.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/format@expression__fstring.py.snap @@ -30,6 +30,15 @@ result_f = ( r' \[Previous line repeated (\d+) more times\]' '\n' 'RecursionError: maximum recursion depth exceeded\n' ) + + +# Regression for fstring dropping comments that were accidentally attached to +# an expression inside a formatted value +( + f'{1}' + # comment + '' +) ``` ## Output @@ -58,6 +67,15 @@ result_f = ( "\n" "RecursionError: maximum recursion depth exceeded\n" ) + + +# Regression for fstring dropping comments that were accidentally attached to +# an expression inside a formatted value +( + f"{1}" + # comment + "" +) ```