Skip to content

Commit dea6553

Browse files
Fix placement for comments within f-strings concatenations (#7047)
## Summary Restores the dangling comment handling for f-strings, which broke with the parenthesized expression code. Closes #6898. ## Test Plan `cargo test` No change in any of the similarity indexes or changed file counts: | project | similarity index | total files | changed files | |--------------|------------------:|------------------:|------------------:| | cpython | 0.76083 | 1789 | 1632 | | django | 0.99957 | 2760 | 67 | | transformers | 0.99927 | 2587 | 468 | | twine | 0.99982 | 33 | 1 | | typeshed | 0.99978 | 3496 | 2173 | | warehouse | 0.99818 | 648 | 24 | | zulip | 0.99942 | 1437 | 32 |
1 parent fbc9b5a commit dea6553

File tree

3 files changed

+86
-0
lines changed

3 files changed

+86
-0
lines changed

crates/ruff_python_formatter/resources/test/fixtures/ruff/expression/fstring.py

+24
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,27 @@
3333
# comment
3434
''
3535
)
36+
37+
(
38+
f'{1}' # comment
39+
f'{2}'
40+
)
41+
42+
(
43+
f'{1}'
44+
f'{2}' # comment
45+
)
46+
47+
(
48+
1, ( # comment
49+
f'{2}'
50+
)
51+
)
52+
53+
(
54+
(
55+
f'{1}'
56+
# comment
57+
),
58+
2
59+
)

crates/ruff_python_formatter/src/comments/placement.rs

+14
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,20 @@ fn handle_parenthesized_comment<'a>(
7070
comment: DecoratedComment<'a>,
7171
locator: &Locator,
7272
) -> CommentPlacement<'a> {
73+
// As a special-case, ignore comments within f-strings, like:
74+
// ```python
75+
// (
76+
// f'{1}' # comment
77+
// f'{2}'
78+
// )
79+
// ```
80+
// These can't be parenthesized, as they must fall between two string tokens in an implicit
81+
// concatenation. But the expression ranges only include the `1` and `2` above, so we also
82+
// can't lex the contents between them.
83+
if comment.enclosing_node().is_expr_f_string() {
84+
return CommentPlacement::Default(comment);
85+
}
86+
7387
let Some(preceding) = comment.preceding_node() else {
7488
return CommentPlacement::Default(comment);
7589
};

crates/ruff_python_formatter/tests/snapshots/format@expression__fstring.py.snap

+48
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,30 @@ result_f = (
3939
# comment
4040
''
4141
)
42+
43+
(
44+
f'{1}' # comment
45+
f'{2}'
46+
)
47+
48+
(
49+
f'{1}'
50+
f'{2}' # comment
51+
)
52+
53+
(
54+
1, ( # comment
55+
f'{2}'
56+
)
57+
)
58+
59+
(
60+
(
61+
f'{1}'
62+
# comment
63+
),
64+
2
65+
)
4266
```
4367

4468
## Output
@@ -76,6 +100,30 @@ result_f = (
76100
# comment
77101
""
78102
)
103+
104+
(
105+
f"{1}" # comment
106+
f"{2}"
107+
)
108+
109+
(
110+
f"{1}" f"{2}" # comment
111+
)
112+
113+
(
114+
1,
115+
( # comment
116+
f"{2}"
117+
),
118+
)
119+
120+
(
121+
(
122+
f"{1}"
123+
# comment
124+
),
125+
2,
126+
)
79127
```
80128

81129

0 commit comments

Comments
 (0)