Skip to content

Commit 5d0a469

Browse files
zsolambv
authored andcommitted
Fix string normalization sometimes producing invalid fstrings (psf#327)
1 parent aad62d3 commit 5d0a469

File tree

3 files changed

+28
-1
lines changed

3 files changed

+28
-1
lines changed

README.md

+5
Original file line numberDiff line numberDiff line change
@@ -807,6 +807,11 @@ More details can be found in [CONTRIBUTING](CONTRIBUTING.md).
807807

808808
## Change Log
809809

810+
### 18.6b3
811+
812+
* fixed improper formatting of f-strings with quotes inside interpolated
813+
expressions (#322)
814+
810815
### 18.6b2
811816

812817
* added `--config` (#65)

black.py

+6
Original file line numberDiff line numberDiff line change
@@ -2549,6 +2549,12 @@ def normalize_string_quotes(leaf: Leaf) -> None:
25492549
leaf.value = f"{prefix}{orig_quote}{body}{orig_quote}"
25502550
new_body = sub_twice(escaped_orig_quote, rf"\1\2{orig_quote}", new_body)
25512551
new_body = sub_twice(unescaped_new_quote, rf"\1\\{new_quote}", new_body)
2552+
if "f" in prefix.casefold():
2553+
matches = re.findall(r"[^{]\{(.*?)\}[^}]", new_body)
2554+
for m in matches:
2555+
if "\\" in str(m):
2556+
# Do not introduce backslashes in interpolated expressions
2557+
return
25522558
if new_quote == '"""' and new_body[-1:] == '"':
25532559
# edge case:
25542560
new_body = new_body[:-1] + '\\"'

tests/data/fstring.py

+17-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,21 @@
11
f"f-string without formatted values is just a string"
22
f"{{NOT a formatted value}}"
3+
f"{{NOT 'a' \"formatted\" \"value\"}}"
34
f"some f-string with {a} {few():.2f} {formatted.values!r}"
4-
f"{f'{nested} inner'} outer"
5+
f'some f-string with {a} {few(""):.2f} {formatted.values!r}'
6+
f"{f'''{'nested'} inner'''} outer"
7+
f"\"{f'{nested} inner'}\" outer"
58
f"space between opening braces: { {a for a in (1, 2, 3)}}"
9+
f'Hello \'{tricky + "example"}\''
10+
11+
# output
12+
13+
f"f-string without formatted values is just a string"
14+
f"{{NOT a formatted value}}"
15+
f'{{NOT \'a\' "formatted" "value"}}'
16+
f"some f-string with {a} {few():.2f} {formatted.values!r}"
17+
f'some f-string with {a} {few(""):.2f} {formatted.values!r}'
18+
f"{f'''{'nested'} inner'''} outer"
19+
f"\"{f'{nested} inner'}\" outer"
20+
f"space between opening braces: { {a for a in (1, 2, 3)}}"
21+
f'Hello \'{tricky + "example"}\''

0 commit comments

Comments
 (0)