Commit 5d0a469e authored by Zsolt Dollenstein's avatar Zsolt Dollenstein Committed by Łukasz Langa
Browse files

Fix string normalization sometimes producing invalid fstrings (#327)

parent aad62d3d
Loading
Loading
Loading
Loading
+5 −0
Changes for README.md: 5 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -807,6 +807,11 @@ More details can be found in [CONTRIBUTING](CONTRIBUTING.md).

## Change Log

### 18.6b3

* fixed improper formatting of f-strings with quotes inside interpolated
  expressions (#322)

### 18.6b2

* added `--config` (#65)
+6 −0
Changes for black.py: 6 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -2549,6 +2549,12 @@ def normalize_string_quotes(leaf: Leaf) -> None:
            leaf.value = f"{prefix}{orig_quote}{body}{orig_quote}"
        new_body = sub_twice(escaped_orig_quote, rf"\1\2{orig_quote}", new_body)
        new_body = sub_twice(unescaped_new_quote, rf"\1\\{new_quote}", new_body)
    if "f" in prefix.casefold():
        matches = re.findall(r"[^{]\{(.*?)\}[^}]", new_body)
        for m in matches:
            if "\\" in str(m):
                # Do not introduce backslashes in interpolated expressions
                return
    if new_quote == '"""' and new_body[-1:] == '"':
        # edge case:
        new_body = new_body[:-1] + '\\"'
+17 −1
Changes for tests/data/fstring.py: 17 added lines, 1 removed line.
Original line number Diff line number Diff line
f"f-string without formatted values is just a string"
f"{{NOT a formatted value}}"
f"{{NOT 'a' \"formatted\" \"value\"}}"
f"some f-string with {a} {few():.2f} {formatted.values!r}"
f"{f'{nested} inner'} outer"
f'some f-string with {a} {few(""):.2f} {formatted.values!r}'
f"{f'''{'nested'} inner'''} outer"
f"\"{f'{nested} inner'}\" outer"
f"space between opening braces: { {a for a in (1, 2, 3)}}"
f'Hello \'{tricky + "example"}\''

# output

f"f-string without formatted values is just a string"
f"{{NOT a formatted value}}"
f'{{NOT \'a\' "formatted" "value"}}'
f"some f-string with {a} {few():.2f} {formatted.values!r}"
f'some f-string with {a} {few(""):.2f} {formatted.values!r}'
f"{f'''{'nested'} inner'''} outer"
f"\"{f'{nested} inner'}\" outer"
f"space between opening braces: { {a for a in (1, 2, 3)}}"
f'Hello \'{tricky + "example"}\''