fix: avoid formatting backslash strings inside f-strings (#4401)

This commit is contained in:
Tushar Sadhwani 2024-07-11 08:22:37 +05:30 committed by GitHub
parent 7e2afc9bfd
commit 721dff5493
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 18 additions and 0 deletions

View File

@ -34,6 +34,9 @@
- Fix regression where Black failed to parse a multiline f-string containing another
multiline string (#4339)
- Fix regression where Black failed to parse an escaped single quote inside an f-string
(#4401)
- Fix bug with Black incorrectly parsing empty lines with a backslash (#4343)
### Performance

View File

@ -510,6 +510,15 @@ def visit_fstring(self, node: Node) -> Iterator[Line]:
# currently we don't want to format and split f-strings at all.
string_leaf = fstring_to_string(node)
node.replace(string_leaf)
if "\\" in string_leaf.value and any(
"\\" in str(child)
for child in node.children
if child.type == syms.fstring_replacement_field
):
# string normalization doesn't account for nested quotes,
# causing breakages. skip normalization when nested quotes exist
yield from self.visit_default(string_leaf)
return
yield from self.visit_STRING(string_leaf)
# TODO: Uncomment Implementation to format f-string children

View File

@ -128,6 +128,9 @@
f"""{'''
'''}"""
f"{'\''}"
f"{f'\''}"
# output
x = f"foo"
@ -258,3 +261,6 @@
f"""{'''
'''}"""
f"{'\''}"
f"{f'\''}"