Skip to content

Commit 721dff5

Browse files
fix: avoid formatting backslash strings inside f-strings (#4401)
1 parent 7e2afc9 commit 721dff5

File tree

3 files changed

+18
-0
lines changed

3 files changed

+18
-0
lines changed

CHANGES.md

+3
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@
3434
- Fix regression where Black failed to parse a multiline f-string containing another
3535
multiline string (#4339)
3636

37+
- Fix regression where Black failed to parse an escaped single quote inside an f-string
38+
(#4401)
39+
3740
- Fix bug with Black incorrectly parsing empty lines with a backslash (#4343)
3841

3942
### Performance

src/black/linegen.py

+9
Original file line numberDiff line numberDiff line change
@@ -510,6 +510,15 @@ def visit_fstring(self, node: Node) -> Iterator[Line]:
510510
# currently we don't want to format and split f-strings at all.
511511
string_leaf = fstring_to_string(node)
512512
node.replace(string_leaf)
513+
if "\\" in string_leaf.value and any(
514+
"\\" in str(child)
515+
for child in node.children
516+
if child.type == syms.fstring_replacement_field
517+
):
518+
# string normalization doesn't account for nested quotes,
519+
# causing breakages. skip normalization when nested quotes exist
520+
yield from self.visit_default(string_leaf)
521+
return
513522
yield from self.visit_STRING(string_leaf)
514523

515524
# TODO: Uncomment Implementation to format f-string children

tests/data/cases/pep_701.py

+6
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,9 @@
128128
f"""{'''
129129
'''}"""
130130

131+
f"{'\''}"
132+
f"{f'\''}"
133+
131134
# output
132135

133136
x = f"foo"
@@ -258,3 +261,6 @@
258261

259262
f"""{'''
260263
'''}"""
264+
265+
f"{'\''}"
266+
f"{f'\''}"

0 commit comments

Comments
 (0)