Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion Lib/ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -1346,10 +1346,20 @@ def visit_Call(self, node):
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)
Expand Down
10 changes: 9 additions & 1 deletion Lib/test/test_unparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -279,10 +279,13 @@ def test_dict_unpacking_in_dict(self):
self.check_ast_roundtrip(r"""{**{'y': 2}, 'x': 1}""")
self.check_ast_roundtrip(r"""{**{'y': 2}, **{'x': 1}}""")

def test_ext_slices(self):
def test_slices(self):
self.check_ast_roundtrip("a[i]")
self.check_ast_roundtrip("a[i,]")
self.check_ast_roundtrip("a[i, j]")
self.check_ast_roundtrip("a[(*a,)]")
self.check_ast_roundtrip("a[(a:=b)]")
self.check_ast_roundtrip("a[(a:=b,c)]")
self.check_ast_roundtrip("a[()]")
self.check_ast_roundtrip("a[i:j]")
self.check_ast_roundtrip("a[:j]")
Expand Down Expand Up @@ -466,6 +469,11 @@ def test_unary_op_factor(self):
for prefix in ("not",):
self.check_src_roundtrip(f"{prefix} 1")

def test_slices(self):
self.check_src_roundtrip("a[1]")
self.check_src_roundtrip("a[1, 2]")
self.check_src_roundtrip("a[(1, *a)]")

class DirectoryTestCase(ASTTestCase):
"""Test roundtrip behaviour on all files in Lib and Lib/test."""

Expand Down