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

Combine f-strings which would be placed on the same line #4480

Closed
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
2 changes: 2 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

<!-- Changes that affect Black's stable style -->

- Combine multiple f-strings into a single f-string when appropriate (#4480)

### Preview style

<!-- Changes that affect Black's preview style -->
Expand Down
35 changes: 35 additions & 0 deletions src/black/linegen.py
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,41 @@ def visit_NUMBER(self, leaf: Leaf) -> Iterator[Line]:
normalize_numeric_literal(leaf)
yield from self.visit_default(leaf)

def visit_atom(self, node: Node) -> Iterator[Line]:
# Addressing https://github.com/psf/black/issues/4389
# turn an atom with only f-strings into a single f-string
# but only if doing so won't go over the line limit
is_all_fstring = True
for c in node.children:
if c.type != syms.fstring:
is_all_fstring = False
break
total_len = len("".join([c.value for c in node.leaves()]))
if (
len(node.children) > 0
and is_all_fstring
and total_len < self.mode.line_length
):
new_node = Node(syms.fstring, [])
# remove all FSTRING_START but first and all FSTRING_END but last
new_children = [
gc
for i, c in enumerate(node.children)
for gc in c.children
if (
not (gc.type == token.FSTRING_START and i != 0)
and not (
gc.type == token.FSTRING_END and i != len(node.children) - 1
)
)
]
for c in new_children:
new_node.append_child(c)
node.replace(new_node)
yield from self.visit_fstring(new_node)
else:
yield from self.visit_default(node)

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)
Expand Down
7 changes: 7 additions & 0 deletions tests/data/cases/combine-fstring.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
sep= " "
FSTRING = f"many" f"{sep}" f"tiny" f"{sep}" f"fstrings"

# output

sep = " "
FSTRING = f"many{sep}tiny{sep}fstrings"
13 changes: 13 additions & 0 deletions tests/data/cases/combine-multi-line-fstring.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
sep= " "
FSTRING = (
f"many"
f"{sep}"
f"tiny"
f"{sep}"
f"fstrings"
)

# output

sep = " "
FSTRING = f"many{sep}tiny{sep}fstrings"