summaryrefslogtreecommitdiffstats
path: root/Lib/ast.py
diff options
context:
space:
mode:
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>2023-09-05 20:49:55 (GMT)
committerGitHub <noreply@github.com>2023-09-05 20:49:55 (GMT)
commit495ba70356fc4824aabb7c245b441051dded14e0 (patch)
tree6abcebc7a75ba41db52d50a929c5bc2417536197 /Lib/ast.py
parent460043b5548c736ac784e8a09030799322777af0 (diff)
downloadcpython-495ba70356fc4824aabb7c245b441051dded14e0.zip
cpython-495ba70356fc4824aabb7c245b441051dded14e0.tar.gz
cpython-495ba70356fc4824aabb7c245b441051dded14e0.tar.bz2
[3.12] gh-108469: Update ast.unparse for unescaped quote support from PEP701 [3.12] (GH-108553) (#108960)
Co-authored-by: Anthony Shaw <anthony.p.shaw@gmail.com> Co-authored-by: sunmy2019 <59365878+sunmy2019@users.noreply.github.com>
Diffstat (limited to 'Lib/ast.py')
-rw-r--r--Lib/ast.py31
1 files changed, 10 insertions, 21 deletions
diff --git a/Lib/ast.py b/Lib/ast.py
index a307f3e..f4e542c 100644
--- a/Lib/ast.py
+++ b/Lib/ast.py
@@ -1223,17 +1223,7 @@ class _Unparser(NodeVisitor):
def visit_JoinedStr(self, node):
self.write("f")
- if self._avoid_backslashes:
- with self.buffered() as buffer:
- self._write_fstring_inner(node)
- return self._write_str_avoiding_backslashes("".join(buffer))
-
- # If we don't need to avoid backslashes globally (i.e., we only need
- # to avoid them inside FormattedValues), it's cosmetically preferred
- # to use escaped whitespace. That is, it's preferred to use backslashes
- # for cases like: f"{x}\n". To accomplish this, we keep track of what
- # in our buffer corresponds to FormattedValues and what corresponds to
- # Constant parts of the f-string, and allow escapes accordingly.
+
fstring_parts = []
for value in node.values:
with self.buffered() as buffer:
@@ -1245,11 +1235,14 @@ class _Unparser(NodeVisitor):
new_fstring_parts = []
quote_types = list(_ALL_QUOTES)
for value, is_constant in fstring_parts:
- value, quote_types = self._str_literal_helper(
- value,
- quote_types=quote_types,
- escape_special_whitespace=is_constant,
- )
+ if is_constant:
+ value, quote_types = self._str_literal_helper(
+ value,
+ quote_types=quote_types,
+ escape_special_whitespace=True,
+ )
+ elif "\n" in value:
+ quote_types = [q for q in quote_types if q in _MULTI_QUOTES]
new_fstring_parts.append(value)
value = "".join(new_fstring_parts)
@@ -1271,16 +1264,12 @@ class _Unparser(NodeVisitor):
def visit_FormattedValue(self, node):
def unparse_inner(inner):
- unparser = type(self)(_avoid_backslashes=True)
+ unparser = type(self)()
unparser.set_precedence(_Precedence.TEST.next(), inner)
return unparser.visit(inner)
with self.delimit("{", "}"):
expr = unparse_inner(node.value)
- if "\\" in expr:
- raise ValueError(
- "Unable to avoid backslash in f-string expression part"
- )
if expr.startswith("{"):
# Separate pair of opening brackets as "{ {"
self.write(" ")