Skip to content

Commit

Permalink
Avoid inserting trailing commas within f-strings (#8574)
Browse files Browse the repository at this point in the history
Closes #8556.
  • Loading branch information
charliermarsh authored Nov 9, 2023
1 parent 722687a commit f499f0c
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
4,
)

foo = 3,
foo = 3,

class A(object):
foo = 3
Expand Down Expand Up @@ -639,3 +639,10 @@ def foo(
:20
],
)

# Make sure we don't insert commas within f-strings.
f"""This is a test. {
"Another sentence."
if True else
"Alternative route!"
}"""
Original file line number Diff line number Diff line change
Expand Up @@ -223,11 +223,24 @@ pub(crate) fn trailing_commas(
tokens: &[LexResult],
locator: &Locator,
) {
let mut fstrings = 0u32;
let tokens = tokens
.iter()
.flatten()
// Completely ignore comments -- they just interfere with the logic.
.filter(|&r| !matches!(r, (Tok::Comment(_), _)))
.filter(|(tok, _)| match tok {
// Completely ignore comments -- they just interfere with the logic.
Tok::Comment(_) => false,
// Ignore content within f-strings.
Tok::FStringStart => {
fstrings = fstrings.saturating_add(1);
false
}
Tok::FStringEnd => {
fstrings = fstrings.saturating_sub(1);
false
}
_ => fstrings == 0,
})
.map(Token::from_spanned);
let tokens = [Token::irrelevant(), Token::irrelevant()]
.into_iter()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ COM81.py:45:8: COM818 Trailing comma on bare tuple prohibited
|
43 | )
44 |
45 | foo = 3,
45 | foo = 3,
| ^ COM818
46 |
47 | class A(object):
Expand Down

0 comments on commit f499f0c

Please sign in to comment.