Skip to content

Commit 7fa75e3

Browse files
[3.15] gh-162622: Fix ast.unparse() for literal braces in format specifiers (GH-162623) (#162626)
(cherry picked from commit 8c68eb4) Co-authored-by: tonghuaroot (童话) <tonghuaroot@gmail.com>
1 parent 40cee2b commit 7fa75e3

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
@@ -913,6 +913,12 @@ def test_backslash_in_format_spec(self):
913913

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

916+
def test_braces_in_format_spec(self):
917+
for prefix in "ft":
918+
self.check_ast_roundtrip(prefix + r'"{value:\x7b>3}"')
919+
self.check_ast_roundtrip(prefix + r'"{value:\x7d>3}"')
920+
self.check_ast_roundtrip(r't"{value:\x7bwidth\x7d}"')
921+
916922
def test_quote_in_format_spec(self):
917923
self.check_ast_roundtrip("""f"{x:'}" """)
918924
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)