From 519c06a8cc888d04c6bd19fb808dfde3a151163d Mon Sep 17 00:00:00 2001 From: Zsolt Dollenstein Date: Sun, 26 May 2019 11:58:00 +0200 Subject: [PATCH] Don't introduce quotes to f-string sub-expressions on string boundaries (#871) --- README.md | 3 +++ black.py | 10 +++++++++- tests/data/string_quotes.py | 12 ++++++++++++ 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ead7b61..9d83101 100644 --- a/README.md +++ b/README.md @@ -1034,6 +1034,9 @@ More details can be found in [CONTRIBUTING](CONTRIBUTING.md). * fixed bug that led *Black* format some code with a line length target of 1 (#762) +* *Black* no longer introduces quotes in f-string subexpressions on string + boundaries (#863) + ### 19.3b0 diff --git a/black.py b/black.py index 7ede0b4..7629d9f 100644 --- a/black.py +++ b/black.py @@ -2728,7 +2728,15 @@ def normalize_string_quotes(leaf: Leaf) -> None: 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) + matches = re.findall( + r""" + (?:[^{]|^)\{ # start of the string or a non-{ followed by a single { + ([^{].*?) # contents of the brackets except if begins with {{ + \}(?:[^}]|$) # A } followed by end of the string or a non-} + """, + new_body, + re.VERBOSE, + ) for m in matches: if "\\" in str(m): # Do not introduce backslashes in interpolated expressions diff --git a/tests/data/string_quotes.py b/tests/data/string_quotes.py index 1994dd2..6b68699 100644 --- a/tests/data/string_quotes.py +++ b/tests/data/string_quotes.py @@ -44,6 +44,12 @@ re.compile(r'[\\"]') '\\""' "\\''" 'Lots of \\\\\\\\\'quotes\'' +f'{y * " "} \'{z}\'' +f'{{y * " "}} \'{z}\'' +f'\'{z}\' {y * " "}' +f'{y * x} \'{z}\'' +'\'{z}\' {y * " "}' +'{y * x} \'{z}\'' # output @@ -93,3 +99,9 @@ re.compile(r'[\\"]') '\\""' "\\''" "Lots of \\\\\\\\'quotes'" +f'{y * " "} \'{z}\'' +f"{{y * \" \"}} '{z}'" +f'\'{z}\' {y * " "}' +f"{y * x} '{z}'" +"'{z}' {y * \" \"}" +"{y * x} '{z}'" \ No newline at end of file -- 2.39.5