-
Notifications
You must be signed in to change notification settings - Fork 2k
Closed
Closed
Copy link
Labels
formatterRelated to the formatterRelated to the formatterhelp wantedContributions especially welcomeContributions especially welcomepreviewRelated to preview mode featuresRelated to preview mode features
Description
The new preview style formats
"" f'{1:""}'as
f"{1:\"\"}"This is correct but results in unnecessary escapes. I think we should account for the quotes in format-specs when choosing the preferred quotes for an f-string.
This can be changed here
ruff/crates/ruff_python_formatter/src/string/normalize.rs
Lines 264 to 295 in 113ce84
| if is_f_string_formatting_enabled(context) { | |
| // For f-strings, only consider the quotes inside string-literals but ignore | |
| // quotes inside expressions. This allows both the outer and the nested literals | |
| // to make the optimal local-choice to reduce the total number of quotes necessary. | |
| // This doesn't require any pre 312 special handling because an expression | |
| // can never contain the outer quote character, not even escaped: | |
| // ```python | |
| // f"{'escaping a quote like this \" is a syntax error pre 312'}" | |
| // ``` | |
| let mut literals = fstring.elements.literals(); | |
| let Some(first) = literals.next() else { | |
| return QuoteMetadata::from_str("", part.flags(), preferred_quote); | |
| }; | |
| let mut metadata = QuoteMetadata::from_str( | |
| context.locator().slice(first.range()), | |
| fstring.flags.into(), | |
| preferred_quote, | |
| ); | |
| for literal in literals { | |
| metadata = metadata | |
| .merge(&QuoteMetadata::from_str( | |
| context.locator().slice(literal.range()), | |
| fstring.flags.into(), | |
| preferred_quote, | |
| )) | |
| .expect("Merge to succeed because all parts have the same flags"); | |
| } | |
| metadata |
CC: @dhruvmanila
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
formatterRelated to the formatterRelated to the formatterhelp wantedContributions especially welcomeContributions especially welcomepreviewRelated to preview mode featuresRelated to preview mode features