]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-44081: improve ast.unparse() for lambdas with no parameters (GH-26000)
authorBatuhan Taskaya <isidentical@gmail.com>
Sat, 15 May 2021 12:55:53 +0000 (15:55 +0300)
committerGitHub <noreply@github.com>
Sat, 15 May 2021 12:55:53 +0000 (15:55 +0300)
Lib/ast.py
Lib/test/test_unparse.py
Misc/NEWS.d/next/Library/2021-05-09-03-26-31.bpo-44081.A-Mrto.rst [new file with mode: 0644]

index 18163d6b7bd1634840d98588afd95db064e0d9eb..0aef172516b3fda9177396c00aa672d42ed85be0 100644 (file)
@@ -716,9 +716,9 @@ class _Unparser(NodeVisitor):
         self.maybe_newline()
         self.write("    " * self._indent + text)
 
-    def write(self, text):
-        """Append a piece of text"""
-        self._source.append(text)
+    def write(self, *text):
+        """Add new source parts"""
+        self._source.extend(text)
 
     @contextmanager
     def buffered(self, buffer = None):
@@ -1566,8 +1566,11 @@ class _Unparser(NodeVisitor):
 
     def visit_Lambda(self, node):
         with self.require_parens(_Precedence.TEST, node):
-            self.write("lambda ")
-            self.traverse(node.args)
+            self.write("lambda")
+            with self.buffered() as buffer:
+                self.traverse(node.args)
+            if buffer:
+                self.write(" ", *buffer)
             self.write(": ")
             self.set_precedence(_Precedence.TEST, node.body)
             self.traverse(node.body)
index 534431bc9698357ea47cfdf8321cc0e3a7f10208..4d3340e26ff02fb308dee0e114c07f9f74946835 100644 (file)
@@ -531,6 +531,17 @@ class CosmeticTestCase(ASTTestCase):
         self.check_src_roundtrip("a[1, 2]")
         self.check_src_roundtrip("a[(1, *a)]")
 
+    def test_lambda_parameters(self):
+        self.check_src_roundtrip("lambda: something")
+        self.check_src_roundtrip("four = lambda: 2 + 2")
+        self.check_src_roundtrip("lambda x: x * 2")
+        self.check_src_roundtrip("square = lambda n: n ** 2")
+        self.check_src_roundtrip("lambda x, y: x + y")
+        self.check_src_roundtrip("add = lambda x, y: x + y")
+        self.check_src_roundtrip("lambda x, y, /, z, q, *, u: None")
+        self.check_src_roundtrip("lambda x, *y, **z: None")
+
+
 class DirectoryTestCase(ASTTestCase):
     """Test roundtrip behaviour on all files in Lib and Lib/test."""
 
diff --git a/Misc/NEWS.d/next/Library/2021-05-09-03-26-31.bpo-44081.A-Mrto.rst b/Misc/NEWS.d/next/Library/2021-05-09-03-26-31.bpo-44081.A-Mrto.rst
new file mode 100644 (file)
index 0000000..e4a09e3
--- /dev/null
@@ -0,0 +1,2 @@
+:func:`ast.unparse` now doesn't use redundant spaces to separate ``lambda``
+and the ``:`` if there are no parameters.