Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: don't try to format strings inside f-strings #4401

Merged
merged 3 commits into from
Jul 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions src/black/linegen.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions tests/data/cases/pep_701.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,9 @@
f"""{'''
'''}"""

f"{'\''}"
f"{f'\''}"

# output

x = f"foo"
Expand Down Expand Up @@ -258,3 +261,6 @@

f"""{'''
'''}"""

f"{'\''}"
f"{f'\''}"
Loading