Skip to content

Commit 65b0310

Browse files
[3.8] bpo-39889: Fix unparse.py for subscript. (GH-18824). (GH-18826)
(cherry picked from commit c4928fc) (cherry picked from commit 92b7278) Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
1 parent 47b7c22 commit 65b0310

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
@@ -260,6 +260,20 @@ def test_dict_unpacking_in_dict(self):
260260
self.check_roundtrip(r"""{**{'y': 2}, 'x': 1}""")
261261
self.check_roundtrip(r"""{**{'y': 2}, **{'x': 1}}""")
262262

263+
def test_subscript(self):
264+
self.check_roundtrip("a[i]")
265+
self.check_roundtrip("a[i,]")
266+
self.check_roundtrip("a[i, j]")
267+
self.check_roundtrip("a[()]")
268+
self.check_roundtrip("a[i:j]")
269+
self.check_roundtrip("a[:j]")
270+
self.check_roundtrip("a[i:]")
271+
self.check_roundtrip("a[i:j:k]")
272+
self.check_roundtrip("a[:j:k]")
273+
self.check_roundtrip("a[i::k]")
274+
self.check_roundtrip("a[i:j,]")
275+
self.check_roundtrip("a[i:j, k]")
276+
263277

264278
class DirectoryTestCase(ASTTestCase):
265279
"""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
@@ -562,7 +562,17 @@ def _Call(self, t):
562562
def _Subscript(self, t):
563563
self.dispatch(t.value)
564564
self.write("[")
565-
self.dispatch(t.slice)
565+
if (isinstance(t.slice, ast.Index)
566+
and isinstance(t.slice.value, ast.Tuple)
567+
and t.slice.value.elts):
568+
if len(t.slice.value.elts) == 1:
569+
elt = t.slice.value.elts[0]
570+
self.dispatch(elt)
571+
self.write(",")
572+
else:
573+
interleave(lambda: self.write(", "), self.dispatch, t.slice.value.elts)
574+
else:
575+
self.dispatch(t.slice)
566576
self.write("]")
567577

568578
def _Starred(self, t):
@@ -587,7 +597,12 @@ def _Slice(self, t):
587597
self.dispatch(t.step)
588598

589599
def _ExtSlice(self, t):
590-
interleave(lambda: self.write(', '), self.dispatch, t.dims)
600+
if len(t.dims) == 1:
601+
elt = t.dims[0]
602+
self.dispatch(elt)
603+
self.write(",")
604+
else:
605+
interleave(lambda: self.write(', '), self.dispatch, t.dims)
591606

592607
# argument
593608
def _arg(self, t):

0 commit comments

Comments
 (0)