mirror of https://github.com/python/cpython
bpo-39889: Fix ast.unparse() for subscript. (GH-18824)
This commit is contained in:
parent
31350f9af0
commit
c4928fc1a8
15
Lib/ast.py
15
Lib/ast.py
|
@ -1261,6 +1261,16 @@ class _Unparser(NodeVisitor):
|
||||||
self.set_precedence(_Precedence.ATOM, node.value)
|
self.set_precedence(_Precedence.ATOM, node.value)
|
||||||
self.traverse(node.value)
|
self.traverse(node.value)
|
||||||
with self.delimit("[", "]"):
|
with self.delimit("[", "]"):
|
||||||
|
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)
|
self.traverse(node.slice)
|
||||||
|
|
||||||
def visit_Starred(self, node):
|
def visit_Starred(self, node):
|
||||||
|
@ -1286,6 +1296,11 @@ class _Unparser(NodeVisitor):
|
||||||
self.traverse(node.step)
|
self.traverse(node.step)
|
||||||
|
|
||||||
def visit_ExtSlice(self, node):
|
def visit_ExtSlice(self, node):
|
||||||
|
if len(node.dims) == 1:
|
||||||
|
elt = node.dims[0]
|
||||||
|
self.traverse(elt)
|
||||||
|
self.write(",")
|
||||||
|
else:
|
||||||
self.interleave(lambda: self.write(", "), self.traverse, node.dims)
|
self.interleave(lambda: self.write(", "), self.traverse, node.dims)
|
||||||
|
|
||||||
def visit_arg(self, node):
|
def visit_arg(self, node):
|
||||||
|
|
|
@ -344,6 +344,20 @@ class CosmeticTestCase(ASTTestCase):
|
||||||
self.check_src_roundtrip("call((yield x))")
|
self.check_src_roundtrip("call((yield x))")
|
||||||
self.check_src_roundtrip("return x + (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):
|
def test_docstrings(self):
|
||||||
docstrings = (
|
docstrings = (
|
||||||
'"""simple doc string"""',
|
'"""simple doc string"""',
|
||||||
|
|
|
@ -0,0 +1,3 @@
|
||||||
|
Fixed :func:`ast.unparse` 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]``).
|
Loading…
Reference in New Issue