From 2b8d207318c1bd469ac0a4ab8cde781f2ea5f1fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?tonghuaroot=20=28=E7=AB=A5=E8=AF=9D=29?= Date: Thu, 26 Nov 2026 00:34:48 +0800 Subject: [PATCH] gh-162622: Fix `ast.unparse()` for literal braces in format specifiers (GH-162623) (cherry picked from commit 8c68eb40c1229cc9e79e16d00e4b8ae8fbbb4b54) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: tonghuaroot (童话) --- Lib/_ast_unparse.py | 6 ++++-- Lib/test/test_unparse.py | 6 ++++++ .../Library/2026-11-25-20-49-22.gh-issue-162622.qAs2pK.rst | 2 ++ 3 files changed, 12 insertions(+), 2 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2026-11-25-20-49-22.gh-issue-162622.qAs2pK.rst diff --git a/Lib/_ast_unparse.py b/Lib/_ast_unparse.py index 1c8741b5a55483..81eec1697e444c 100644 --- a/Lib/_ast_unparse.py +++ b/Lib/_ast_unparse.py @@ -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) diff --git a/Lib/test/test_unparse.py b/Lib/test/test_unparse.py index 759d5e8f2a6eaa..50e123c9a07357 100644 --- a/Lib/test/test_unparse.py +++ b/Lib/test/test_unparse.py @@ -890,6 +890,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:\\'}" """) diff --git a/Misc/NEWS.d/next/Library/2026-11-25-20-49-22.gh-issue-162622.qAs2pK.rst b/Misc/NEWS.d/next/Library/2026-11-25-20-49-22.gh-issue-162622.qAs2pK.rst new file mode 100644 index 00000000000000..1f6c1b8cf6fe3e --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-25-20-49-22.gh-issue-162622.qAs2pK.rst @@ -0,0 +1,2 @@ +Preserve literal braces in f-string and t-string format specifiers when +using :func:`ast.unparse`.