Skip to content

Commit 92b7278

Browse files
[3.8] bpo-39889: Fix unparse.py for subscript. (GH-18824). (GH-18826)
(cherry picked from commit c4928fc)
1 parent d692d52 commit 92b7278

File tree

3 files changed

+34
-2
lines changed

3 files changed

+34
-2
lines changed

Lib/test/test_tools/test_unparse.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,20 @@ def test_dict_unpacking_in_dict(self):
265265
self.check_roundtrip(r"""{**{'y': 2}, 'x': 1}""")
266266
self.check_roundtrip(r"""{**{'y': 2}, **{'x': 1}}""")
267267

268+
def test_subscript(self):
269+
self.check_roundtrip("a[i]")
270+
self.check_roundtrip("a[i,]")
271+
self.check_roundtrip("a[i, j]")
272+
self.check_roundtrip("a[()]")
273+
self.check_roundtrip("a[i:j]")
274+
self.check_roundtrip("a[:j]")
275+
self.check_roundtrip("a[i:]")
276+
self.check_roundtrip("a[i:j:k]")
277+
self.check_roundtrip("a[:j:k]")
278+
self.check_roundtrip("a[i::k]")
279+
self.check_roundtrip("a[i:j,]")
280+
self.check_roundtrip("a[i:j, k]")
281+
268282

269283
class DirectoryTestCase(ASTTestCase):
270284
"""Test roundtrip behaviour on all files in Lib and Lib/test."""
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fixed ``unparse.py`` for extended slices containing a single element (e.g.
2+
``a[i:j,]``). Remove redundant tuples when index with a tuple (e.g. ``a[i,
3+
j]``).

Tools/parser/unparse.py

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -556,7 +556,17 @@ def _Call(self, t):
556556
def _Subscript(self, t):
557557
self.dispatch(t.value)
558558
self.write("[")
559-
self.dispatch(t.slice)
559+
if (isinstance(t.slice, ast.Index)
560+
and isinstance(t.slice.value, ast.Tuple)
561+
and t.slice.value.elts):
562+
if len(t.slice.value.elts) == 1:
563+
elt = t.slice.value.elts[0]
564+
self.dispatch(elt)
565+
self.write(",")
566+
else:
567+
interleave(lambda: self.write(", "), self.dispatch, t.slice.value.elts)
568+
else:
569+
self.dispatch(t.slice)
560570
self.write("]")
561571

562572
def _Starred(self, t):
@@ -581,7 +591,12 @@ def _Slice(self, t):
581591
self.dispatch(t.step)
582592

583593
def _ExtSlice(self, t):
584-
interleave(lambda: self.write(', '), self.dispatch, t.dims)
594+
if len(t.dims) == 1:
595+
elt = t.dims[0]
596+
self.dispatch(elt)
597+
self.write(",")
598+
else:
599+
interleave(lambda: self.write(', '), self.dispatch, t.dims)
585600

586601
# argument
587602
def _arg(self, t):

0 commit comments

Comments
 (0)