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`.