Skip to content
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
6 changes: 4 additions & 2 deletions Lib/_ast_unparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -638,13 +638,15 @@ def _write_ftstring_inner(self, node, is_format_spec=False):
for value in node.values:
self._write_ftstring_inner(value, is_format_spec=is_format_spec)
elif isinstance(node, Constant) and isinstance(node.value, str):
value = node.value.replace("{", "{{").replace("}", "}}")

value = node.value
if is_format_spec:
value = value.replace("\\", "\\\\")
value = value.replace("{", "\\x7b").replace("}", "\\x7d")
value = value.replace("'", "\\'")
value = value.replace('"', '\\"')
value = value.replace("\n", "\\n")
else:
value = value.replace("{", "{{").replace("}", "}}")
self.write(value)
elif isinstance(node, FormattedValue):
self.visit_FormattedValue(node)
Expand Down
6 changes: 6 additions & 0 deletions Lib/test/test_unparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -921,6 +921,12 @@ def test_backslash_in_format_spec(self):

self.check_ast_roundtrip("""f"{x:\\\\\\\\ }" """)

def test_braces_in_format_spec(self):
for prefix in "ft":
self.check_ast_roundtrip(prefix + r'"{value:\x7b>3}"')
self.check_ast_roundtrip(prefix + r'"{value:\x7d>3}"')
self.check_ast_roundtrip(r't"{value:\x7bwidth\x7d}"')

def test_quote_in_format_spec(self):
self.check_ast_roundtrip("""f"{x:'}" """)
self.check_ast_roundtrip("""f"{x:\\'}" """)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Preserve literal braces in f-string and t-string format specifiers when
using :func:`ast.unparse`.
Loading