Skip to content

Aggregate escape counts across all f-string segments in normalize_fstring_quotes#4998

Merged
cobaltt7 merged 1 commit intopsf:mainfrom
bysiber:fix-fstring-escape-count-aggregation
Feb 21, 2026
Merged

Aggregate escape counts across all f-string segments in normalize_fstring_quotes#4998
cobaltt7 merged 1 commit intopsf:mainfrom
bysiber:fix-fstring-escape-count-aggregation

Conversation

@bysiber
Copy link
Copy Markdown
Contributor

@bysiber bysiber commented Feb 20, 2026

In normalize_fstring_quotes, the loop that checks whether quote normalization would introduce more escaping overwrites orig_escape_count and new_escape_count on each iteration:

for middle, new_segment in zip(middles, new_segments, strict=True):
    orig_escape_count = middle.value.count("\\")
    new_escape_count = new_segment.count("\\")

if new_escape_count > orig_escape_count:
    return middles, quote  # Do not introduce more escaping

After the loop finishes, both variables only hold the counts from the last segment. For an f-string with multiple text segments (e.g. f'text1{expr}text2'), a newly-introduced escape in an earlier segment is ignored entirely.

This changes the loop to aggregate the counts across all segments:

orig_escape_count = 0
new_escape_count = 0
for middle, new_segment in zip(middles, new_segments, strict=True):
    orig_escape_count += middle.value.count("\\")
    new_escape_count += new_segment.count("\\")

Note: this function is currently only referenced in a commented-out block in linegen.py, so there's no runtime impact today. But the fix is worth having before f-string quote normalization is enabled.

@github-actions
Copy link
Copy Markdown
Contributor

diff-shades results comparing this PR (9846ad2) to main (5518079):

--preview style: no changes

--stable style: no changes


What is this? | Workflow run | diff-shades documentation

@JelleZijlstra JelleZijlstra added the ci: skip news Pull requests that don't need a changelog entry. label Feb 20, 2026
@cobaltt7 cobaltt7 merged commit bd84c7e into psf:main Feb 21, 2026
56 of 57 checks passed
cobaltt7 pushed a commit to cobaltt7/black that referenced this pull request Feb 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci: skip news Pull requests that don't need a changelog entry.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants