Skip to content

Commit 8c68eb4

Browse files
authored
gh-162622: Fix ast.unparse() for literal braces in format specifiers (#162623)
1 parent efd7aac commit 8c68eb4

3 files changed

Lines changed: 12 additions & 2 deletions

File tree

‎Lib/_ast_unparse.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -638,13 +638,15 @@ def _write_ftstring_inner(self, node, is_format_spec=False):
638638
for value in node.values:
639639
self._write_ftstring_inner(value, is_format_spec=is_format_spec)
640640
elif isinstance(node, Constant) and isinstance(node.value, str):
641-
value = node.value.replace("{", "{{").replace("}", "}}")
642-
641+
value = node.value
643642
if is_format_spec:
644643
value = value.replace("\\", "\\\\")
644+
value = value.replace("{", "\\x7b").replace("}", "\\x7d")
645645
value = value.replace("'", "\\'")
646646
value = value.replace('"', '\\"')
647647
value = value.replace("\n", "\\n")
648+
else:
649+
value = value.replace("{", "{{").replace("}", "}}")
648650
self.write(value)
649651
elif isinstance(node, FormattedValue):
650652
self.visit_FormattedValue(node)

‎Lib/test/test_unparse.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -921,6 +921,12 @@ def test_backslash_in_format_spec(self):
921921

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

924+
def test_braces_in_format_spec(self):
925+
for prefix in "ft":
926+
self.check_ast_roundtrip(prefix + r'"{value:\x7b>3}"')
927+
self.check_ast_roundtrip(prefix + r'"{value:\x7d>3}"')
928+
self.check_ast_roundtrip(r't"{value:\x7bwidth\x7d}"')
929+
924930
def test_quote_in_format_spec(self):
925931
self.check_ast_roundtrip("""f"{x:'}" """)
926932
self.check_ast_roundtrip("""f"{x:\\'}" """)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Preserve literal braces in f-string and t-string format specifiers when
2+
using :func:`ast.unparse`.

0 commit comments

Comments
 (0)