-
-
Notifications
You must be signed in to change notification settings - Fork 32.6k
gh-108469: Update ast.unparse for unescaped quote support from PEP701 [3.12] #108553
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 9 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
5ee5d57
Add two tests for ast.unparse for unescaped quote support from PEP701
tonybaloney 20b6455
Merge branch 'main' into unparse_pep701
tonybaloney d9bf98a
Merge branch 'main' into unparse_pep701
sunmy2019 cb043e0
unparse with new fstring syntax
sunmy2019 5ea8f4f
Add news
sunmy2019 e716e03
Merge branch 'main' into unparse_pep701
sunmy2019 1da1d4c
Update Lib/test/test_unparse.py
sunmy2019 43d177c
simplify things
sunmy2019 21229ce
reimplement quote selection logic
sunmy2019 9b1b5dd
Revert "reimplement quote selection logic"
sunmy2019 88394d1
clean up unnecessary parts
sunmy2019 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -1225,37 +1225,49 @@ def _write_str_avoiding_backslashes(self, string, *, quote_types=_ALL_QUOTES): | |
|
||
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: | ||
self._write_fstring_inner(value) | ||
fstring_parts.append( | ||
("".join(buffer), isinstance(value, Constant)) | ||
) | ||
fstring_parts.append(("".join(buffer), isinstance(value, Constant))) | ||
|
||
# We decide if we need to write a multi-line `f-string` since it is only | ||
# necessary when we have "\n" inside formatted values. | ||
use_multiline = any( | ||
"\n" in value for value, is_constant in fstring_parts if not is_constant | ||
) | ||
|
||
# We then choose the quote type we use. We let `repr` do this work for | ||
# now. This can be easily modified afterwards. | ||
quote = repr( | ||
"".join(value for value, is_constant in fstring_parts if is_constant) | ||
)[0] | ||
quote_type = quote * 3 if use_multiline else quote | ||
|
||
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: | ||
consecutive_quotes = 0 | ||
res = [] | ||
for c in value: | ||
if c == "\\" or not c.isprintable(): | ||
res.append(c.encode("unicode_escape").decode("ascii")) | ||
continue | ||
if c == quote: | ||
if consecutive_quotes == len(quote_type) - 1: | ||
# escape when we see a full `quote_type` | ||
res.append("\\") | ||
consecutive_quotes = 0 | ||
else: | ||
consecutive_quotes += 1 | ||
else: | ||
consecutive_quotes = 0 | ||
res.append(c) | ||
value = "".join(res) | ||
new_fstring_parts.append(value) | ||
|
||
value = "".join(new_fstring_parts) | ||
quote_type = quote_types[0] | ||
self.write(f"{quote_type}{value}{quote_type}") | ||
|
||
def _write_fstring_inner(self, node): | ||
|
@@ -1273,16 +1285,12 @@ def _write_fstring_inner(self, node): | |
|
||
def visit_FormattedValue(self, node): | ||
def unparse_inner(inner): | ||
unparser = type(self)(_avoid_backslashes=True) | ||
unparser = type(self)(_avoid_backslashes=False) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do we still need this mode or can we drop There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I guess we can drop it. |
||
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(" ") | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
3 changes: 3 additions & 0 deletions
3
Misc/NEWS.d/next/Library/2023-09-03-04-37-52.gh-issue-108469.kusj40.rst
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
:func:`ast.unparse` now supports new :term:`f-string` syntax introduced in | ||
Python 3.12. Note that the :term:`f-string` quotes are reselected for simplicity | ||
under the new syntax. (Patch by Steven Sun) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This logic probably belongs somewhere else, something similiar to what we had with the existing f-string unparsing implementation:
https://github.com/python/cpython/blob/21229ce1f0c8fb2e580df62972296d629960f30e/Lib/ast.py#L1182C1-L1218C1