black
black copied to clipboard
Remove trailing spaces in f-string expressions
Description
Added a new feature in preview mode: Black now knows how to trim trailing whitespaces inside f-strings.
For example the following code:
print(f"there are { 2 } unnecessary spaces in this f string")
print(f"there are { 3} unnecessary spaces on the left")
print(f"there are {3 } unnecessary spaces on the right")
print(f"you should trim { 'me' } and { 'me!' }")
print(f"trimming is easy as { 1 + 1 } == {2}")
will transform to:
print(f"there are {2} unnecessary spaces in this f string")
print(f"there are {3} unnecessary spaces on the left")
print(f"there are {3} unnecessary spaces on the right")
print(f"you should trim {'me'} and {'me!'}")
print(f"trimming is easy as {1 + 1} == {2}")
Checklist - did you ...
- [x] Add a CHANGELOG entry if necessary?
- [X] Add / update tests if necessary?
- [ ] Add new / update outdated documentation?
diff-shades results comparing this PR (dd6d6aef86a3659b99c7a566cc414559c1a644b8) to main (162ecd1d2cf9471efefb5b61c17d28b73acb79a1). The full diff is available in the logs under the "Generate HTML diff report" step.
╭─────────────────────── Summary ────────────────────────╮
│ 5 projects & 22 files changed / 134 changes [+61/-73] │
│ │
│ ... out of 2 233 534 lines, 10 633 files & 23 projects │
╰────────────────────────────────────────────────────────╯
Differences found.
Hey, thanks for taking a stab at this. I have two concerns:
- This only solves the problem partially. prefix and postfix spaces will be stripped, but the rest of the expression won't be formatted
- I think the PR is not quite ready yet. Consider
f'ok { expr = !r: aosidjhoi } end', orf'{ bar : { baz } }'. Both of these cause Black to fail on this PR because of unstable formatting
Hey @zsol .
Thanks for the feedback! I think I've fixed everything you've mentioned, but let me know if I missed something.
This has a lot of merge conflicts now.
I'm feeling conflicted about this PR.
On the one hand, this PR does what it says it should do. solving the merge conflicts should not be an issue. On the other hand, I think that a better approach is to finally add f-string parsing to blib2to3. It all seems too much of a hack to me.
If we want to take the second approach, this PR need to be closed and splitted to 2 new PRs:
- Adding f-string parsing to blib2to3
- Using this new node to parse elements inside f-string proprly.
What do you think we should do? should we proceed with this PR and do a makeover later, or should we close this PR and do it again, the right way this time?
I would prefer to do proper full formatting of f-string contents (which doesn't necessarily require blib2to3 changes; we could do it inside black). I don't think there is enough value in piecemeal changes to fix minor aspects of f-string formatting.
Ok. Closing this PR in favor of a more thorough change.