Skip to content

f-string formatting: Consider format specs when choosing the preferred quotes #13935

@MichaReiser

Description

@MichaReiser

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

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    formatterRelated to the formatterhelp wantedContributions especially welcomepreviewRelated to preview mode features

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions