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

[3.11] gh-108843: fix ast.unparse for f-string with many quotes #108980

Merged
merged 3 commits into from
Sep 18, 2023
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
18 changes: 17 additions & 1 deletion Lib/ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -1175,13 +1175,29 @@ def visit_JoinedStr(self, node):

new_fstring_parts = []
quote_types = list(_ALL_QUOTES)
fallback_to_repr = False
for value, is_constant in fstring_parts:
value, quote_types = self._str_literal_helper(
value, new_quote_types = self._str_literal_helper(
value,
quote_types=quote_types,
escape_special_whitespace=is_constant,
)
new_fstring_parts.append(value)
if set(new_quote_types).isdisjoint(quote_types):
fallback_to_repr = True
break
quote_types = new_quote_types

if fallback_to_repr:
# If we weren't able to find a quote type that works for all parts
# of the JoinedStr, fallback to using repr and triple single quotes.
quote_types = ["'''"]
new_fstring_parts.clear()
for value, is_constant in fstring_parts:
value = repr('"' + value) # force repr to use single quotes
expected_prefix = "'\""
assert value.startswith(expected_prefix), repr(value)
new_fstring_parts.append(value[len(expected_prefix):-1])

value = "".join(new_fstring_parts)
quote_type = quote_types[0]
Expand Down
5 changes: 5 additions & 0 deletions Lib/test/test_unparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -662,6 +662,11 @@ def test_star_expr_assign_target_multiple(self):
self.check_src_roundtrip("[a, b] = [c, d] = [e, f] = g")
self.check_src_roundtrip("a, b = [c, d] = e, f = g")

def test_multiquote_joined_string(self):
self.check_ast_roundtrip("f\"'''{1}\\\"\\\"\\\"\" ")
self.check_ast_roundtrip("""f"'''{1}""\\"" """)
self.check_ast_roundtrip("""f'""\"{1}''' """)
self.check_ast_roundtrip("""f'""\"{1}""\\"' """)


class DirectoryTestCase(ASTTestCase):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix an issue in :func:`ast.unparse` when unparsing f-strings containing many quote types.