summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
authorSerhiy Storchaka <storchaka@gmail.com>2020-03-07 15:25:32 (GMT)
committerGitHub <noreply@github.com>2020-03-07 15:25:32 (GMT)
commitc4928fc1a853f3f84e2b4ec1253d0349137745e5 (patch)
tree4c213e05ad58a09a245a04ac76f8843609da4837 /Lib
parent31350f9af09dcff7cf6ff4b0a0a7ea595942372e (diff)
downloadcpython-c4928fc1a853f3f84e2b4ec1253d0349137745e5.zip
cpython-c4928fc1a853f3f84e2b4ec1253d0349137745e5.tar.gz
cpython-c4928fc1a853f3f84e2b4ec1253d0349137745e5.tar.bz2
bpo-39889: Fix ast.unparse() for subscript. (GH-18824)
Diffstat (limited to 'Lib')
-rw-r--r--Lib/ast.py19
-rw-r--r--Lib/test/test_unparse.py14
2 files changed, 31 insertions, 2 deletions
diff --git a/Lib/ast.py b/Lib/ast.py
index 93ffa1e..2719f6f 100644
--- a/Lib/ast.py
+++ b/Lib/ast.py
@@ -1261,7 +1261,17 @@ class _Unparser(NodeVisitor):
self.set_precedence(_Precedence.ATOM, node.value)
self.traverse(node.value)
with self.delimit("[", "]"):
- self.traverse(node.slice)
+ if (isinstance(node.slice, Index)
+ and isinstance(node.slice.value, Tuple)
+ and node.slice.value.elts):
+ if len(node.slice.value.elts) == 1:
+ elt = node.slice.value.elts[0]
+ self.traverse(elt)
+ self.write(",")
+ else:
+ self.interleave(lambda: self.write(", "), self.traverse, node.slice.value.elts)
+ else:
+ self.traverse(node.slice)
def visit_Starred(self, node):
self.write("*")
@@ -1286,7 +1296,12 @@ class _Unparser(NodeVisitor):
self.traverse(node.step)
def visit_ExtSlice(self, node):
- self.interleave(lambda: self.write(", "), self.traverse, node.dims)
+ if len(node.dims) == 1:
+ elt = node.dims[0]
+ self.traverse(elt)
+ self.write(",")
+ else:
+ self.interleave(lambda: self.write(", "), self.traverse, node.dims)
def visit_arg(self, node):
self.write(node.arg)
diff --git a/Lib/test/test_unparse.py b/Lib/test/test_unparse.py
index d04db4d..d33f32e 100644
--- a/Lib/test/test_unparse.py
+++ b/Lib/test/test_unparse.py
@@ -344,6 +344,20 @@ class CosmeticTestCase(ASTTestCase):
self.check_src_roundtrip("call((yield x))")
self.check_src_roundtrip("return x + (yield x)")
+ def test_subscript(self):
+ self.check_src_roundtrip("a[i]")
+ self.check_src_roundtrip("a[i,]")
+ self.check_src_roundtrip("a[i, j]")
+ self.check_src_roundtrip("a[()]")
+ self.check_src_roundtrip("a[i:j]")
+ self.check_src_roundtrip("a[:j]")
+ self.check_src_roundtrip("a[i:]")
+ self.check_src_roundtrip("a[i:j:k]")
+ self.check_src_roundtrip("a[:j:k]")
+ self.check_src_roundtrip("a[i::k]")
+ self.check_src_roundtrip("a[i:j,]")
+ self.check_src_roundtrip("a[i:j, k]")
+
def test_docstrings(self):
docstrings = (
'"""simple doc string"""',