Skip to content

[3.8] bpo-39889: Fix unparse.py for subscript. (GH-18824). #18826

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 1 commit into from
Mar 7, 2020
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
14 changes: 14 additions & 0 deletions Lib/test/test_tools/test_unparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,20 @@ def test_dict_unpacking_in_dict(self):
self.check_roundtrip(r"""{**{'y': 2}, 'x': 1}""")
self.check_roundtrip(r"""{**{'y': 2}, **{'x': 1}}""")

def test_subscript(self):
self.check_roundtrip("a[i]")
self.check_roundtrip("a[i,]")
self.check_roundtrip("a[i, j]")
self.check_roundtrip("a[()]")
self.check_roundtrip("a[i:j]")
self.check_roundtrip("a[:j]")
self.check_roundtrip("a[i:]")
self.check_roundtrip("a[i:j:k]")
self.check_roundtrip("a[:j:k]")
self.check_roundtrip("a[i::k]")
self.check_roundtrip("a[i:j,]")
self.check_roundtrip("a[i:j, k]")


class DirectoryTestCase(ASTTestCase):
"""Test roundtrip behaviour on all files in Lib and Lib/test."""
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fixed ``unparse.py`` for extended slices containing a single element (e.g.
``a[i:j,]``). Remove redundant tuples when index with a tuple (e.g. ``a[i,
j]``).
19 changes: 17 additions & 2 deletions Tools/parser/unparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -556,7 +556,17 @@ def _Call(self, t):
def _Subscript(self, t):
self.dispatch(t.value)
self.write("[")
self.dispatch(t.slice)
if (isinstance(t.slice, ast.Index)
and isinstance(t.slice.value, ast.Tuple)
and t.slice.value.elts):
if len(t.slice.value.elts) == 1:
elt = t.slice.value.elts[0]
self.dispatch(elt)
self.write(",")
else:
interleave(lambda: self.write(", "), self.dispatch, t.slice.value.elts)
else:
self.dispatch(t.slice)
self.write("]")

def _Starred(self, t):
Expand All @@ -581,7 +591,12 @@ def _Slice(self, t):
self.dispatch(t.step)

def _ExtSlice(self, t):
interleave(lambda: self.write(', '), self.dispatch, t.dims)
if len(t.dims) == 1:
elt = t.dims[0]
self.dispatch(elt)
self.write(",")
else:
interleave(lambda: self.write(', '), self.dispatch, t.dims)

# argument
def _arg(self, t):
Expand Down