diff options
author | Frank Hoffmann <44680962+15r10nk@users.noreply.github.com> | 2024-02-21 10:24:08 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2024-02-21 10:24:08 (GMT) |
commit | 69ab93082d14425aaac48b8393711c716575b132 (patch) | |
tree | b037077bbf9fc6048f6dc18032fb32df48b5dedf /Lib/ast.py | |
parent | 074bbec9c4911da1d1155e56bd1693665800b814 (diff) | |
download | cpython-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.py | 15 |
1 files changed, 8 insertions, 7 deletions
@@ -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) |