summaryrefslogtreecommitdiffstats
path: root/Lib/ast.py
diff options
context:
space:
mode:
authorFrank Hoffmann <44680962+15r10nk@users.noreply.github.com>2024-02-21 10:24:08 (GMT)
committerGitHub <noreply@github.com>2024-02-21 10:24:08 (GMT)
commit69ab93082d14425aaac48b8393711c716575b132 (patch)
treeb037077bbf9fc6048f6dc18032fb32df48b5dedf /Lib/ast.py
parent074bbec9c4911da1d1155e56bd1693665800b814 (diff)
downloadcpython-69ab93082d14425aaac48b8393711c716575b132.zip
cpython-69ab93082d14425aaac48b8393711c716575b132.tar.gz
cpython-69ab93082d14425aaac48b8393711c716575b132.tar.bz2
gh-112364: Correct unparsing of backslashes and quotes in ast.unparse (#115696)
Diffstat (limited to 'Lib/ast.py')
-rw-r--r--Lib/ast.py15
1 files changed, 8 insertions, 7 deletions
diff --git a/Lib/ast.py b/Lib/ast.py
index 43703a8..b8c4ce6 100644
--- a/Lib/ast.py
+++ b/Lib/ast.py
@@ -1269,14 +1269,18 @@ class _Unparser(NodeVisitor):
quote_type = quote_types[0]
self.write(f"{quote_type}{value}{quote_type}")
- def _write_fstring_inner(self, node, escape_newlines=False):
+ def _write_fstring_inner(self, node, is_format_spec=False):
if isinstance(node, JoinedStr):
# for both the f-string itself, and format_spec
for value in node.values:
- self._write_fstring_inner(value, escape_newlines=escape_newlines)
+ self._write_fstring_inner(value, is_format_spec=is_format_spec)
elif isinstance(node, Constant) and isinstance(node.value, str):
value = node.value.replace("{", "{{").replace("}", "}}")
- if escape_newlines:
+
+ if is_format_spec:
+ value = value.replace("\\", "\\\\")
+ value = value.replace("'", "\\'")
+ value = value.replace('"', '\\"')
value = value.replace("\n", "\\n")
self.write(value)
elif isinstance(node, FormattedValue):
@@ -1300,10 +1304,7 @@ class _Unparser(NodeVisitor):
self.write(f"!{chr(node.conversion)}")
if node.format_spec:
self.write(":")
- self._write_fstring_inner(
- node.format_spec,
- escape_newlines=True
- )
+ self._write_fstring_inner(node.format_spec, is_format_spec=True)
def visit_Name(self, node):
self.write(node.id)