mirror of
https://github.com/python/cpython.git
synced 2025-08-27 04:05:34 +00:00
bpo-38870: Don't omit parenthesis when unparsing a slice in ast.unparse
When unparsing a non-empty tuple, the parentheses can be safely omitted if there aren't any elements that explicitly require them (such as starred expressions).
This commit is contained in:
parent
75b863aa97
commit
c102a14825
2 changed files with 20 additions and 2 deletions
12
Lib/ast.py
12
Lib/ast.py
|
@ -1356,10 +1356,20 @@ class _Unparser(NodeVisitor):
|
|||
self.traverse(e)
|
||||
|
||||
def visit_Subscript(self, node):
|
||||
def is_simple_tuple(slice_value):
|
||||
# when unparsing a non-empty tuple, the parantheses can be safely
|
||||
# omitted if there aren't any elements that explicitly requires
|
||||
# parantheses (such as starred expressions).
|
||||
return (
|
||||
isinstance(slice_value, Tuple)
|
||||
and slice_value.elts
|
||||
and not any(isinstance(elt, Starred) for elt in slice_value.elts)
|
||||
)
|
||||
|
||||
self.set_precedence(_Precedence.ATOM, node.value)
|
||||
self.traverse(node.value)
|
||||
with self.delimit("[", "]"):
|
||||
if isinstance(node.slice, Tuple) and node.slice.elts:
|
||||
if is_simple_tuple(node.slice):
|
||||
self.items_view(self.traverse, node.slice.elts)
|
||||
else:
|
||||
self.traverse(node.slice)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue