From 934b3259f917d0bbed8c39c1d14dbb0751b6271d Mon Sep 17 00:00:00 2001 From: Johannes Willkomm Date: Thu, 13 Jul 2023 19:21:14 +0200 Subject: [PATCH 1/2] Add some tests for index expressions, maybe showing bug reharding parentheses --- tests/common.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tests/common.py b/tests/common.py index 95b9755..0c14b13 100644 --- a/tests/common.py +++ b/tests/common.py @@ -293,6 +293,18 @@ def test_raise_from(self): def test_bytes(self): self.check_roundtrip("b'123'") + def test_index(self): + self.check_roundtrip("r[0]") + self.check_roundtrip("r[0:5]") + self.check_roundtrip("r[0:5:2]") + self.check_roundtrip("r[1::2]") + + def test_index2(self): + self.check_roundtrip("r[0,i]") + self.check_roundtrip("r[:,0:5]") + self.check_roundtrip("r[i:1:-1, 2]") + self.check_roundtrip("r[i:1:-1, :]") + @unittest.skipIf(sys.version_info < (3, 6), "Not supported < 3.6") def test_formatted_value(self): self.check_roundtrip('f"{value}"') From 1fa9b73fd5ef30a31cbe090303504123fed95a76 Mon Sep 17 00:00:00 2001 From: Johannes Willkomm Date: Thu, 13 Jul 2023 19:46:51 +0200 Subject: [PATCH 2/2] This fixes the bug regarding parentheses for a Tuple as a slice in Subscript: must not print the parentheses --- lib/astunparse/unparser.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/astunparse/unparser.py b/lib/astunparse/unparser.py index 0ef6fd8..8485705 100644 --- a/lib/astunparse/unparser.py +++ b/lib/astunparse/unparser.py @@ -56,14 +56,14 @@ def leave(self): "Decrease the indentation level." self._indent -= 1 - def dispatch(self, tree): + def dispatch(self, tree, **kw): "Dispatcher function, dispatching tree type T to method _T." if isinstance(tree, list): for t in tree: self.dispatch(t) return meth = getattr(self, "_"+tree.__class__.__name__) - meth(tree) + meth(tree, **(kw if meth.__name__ in ["_Tuple"] else {})) ############### Unparsing methods ###################### @@ -648,15 +648,15 @@ def write_item(item): interleave(lambda: self.write(", "), write_item, zip(t.keys, t.values)) self.write("}") - def _Tuple(self, t): - self.write("(") + def _Tuple(self, t, noparen=False, **kw): + if not noparen: self.write("(") if len(t.elts) == 1: elt = t.elts[0] self.dispatch(elt) self.write(",") else: interleave(lambda: self.write(", "), self.dispatch, t.elts) - self.write(")") + if not noparen: self.write(")") unop = {"Invert":"~", "Not": "not", "UAdd":"+", "USub":"-"} def _UnaryOp(self, t): @@ -741,7 +741,7 @@ def _Call(self, t): def _Subscript(self, t): self.dispatch(t.value) self.write("[") - self.dispatch(t.slice) + self.dispatch(t.slice, noparen=True) self.write("]") def _Starred(self, t):