Skip to content

Commit e4e931a

Browse files
authored
bpo-44081: improve ast.unparse() for lambdas with no parameters (pythonGH-26000)
1 parent 4aa63d6 commit e4e931a

File tree

3 files changed

+21
-5
lines changed

3 files changed

+21
-5
lines changed

Diff for: Lib/ast.py

+8-5
Original file line numberDiff line numberDiff line change
@@ -716,9 +716,9 @@ def fill(self, text=""):
716716
self.maybe_newline()
717717
self.write(" " * self._indent + text)
718718

719-
def write(self, text):
720-
"""Append a piece of text"""
721-
self._source.append(text)
719+
def write(self, *text):
720+
"""Add new source parts"""
721+
self._source.extend(text)
722722

723723
@contextmanager
724724
def buffered(self, buffer = None):
@@ -1566,8 +1566,11 @@ def visit_keyword(self, node):
15661566

15671567
def visit_Lambda(self, node):
15681568
with self.require_parens(_Precedence.TEST, node):
1569-
self.write("lambda ")
1570-
self.traverse(node.args)
1569+
self.write("lambda")
1570+
with self.buffered() as buffer:
1571+
self.traverse(node.args)
1572+
if buffer:
1573+
self.write(" ", *buffer)
15711574
self.write(": ")
15721575
self.set_precedence(_Precedence.TEST, node.body)
15731576
self.traverse(node.body)

Diff for: Lib/test/test_unparse.py

+11
Original file line numberDiff line numberDiff line change
@@ -531,6 +531,17 @@ def test_slices(self):
531531
self.check_src_roundtrip("a[1, 2]")
532532
self.check_src_roundtrip("a[(1, *a)]")
533533

534+
def test_lambda_parameters(self):
535+
self.check_src_roundtrip("lambda: something")
536+
self.check_src_roundtrip("four = lambda: 2 + 2")
537+
self.check_src_roundtrip("lambda x: x * 2")
538+
self.check_src_roundtrip("square = lambda n: n ** 2")
539+
self.check_src_roundtrip("lambda x, y: x + y")
540+
self.check_src_roundtrip("add = lambda x, y: x + y")
541+
self.check_src_roundtrip("lambda x, y, /, z, q, *, u: None")
542+
self.check_src_roundtrip("lambda x, *y, **z: None")
543+
544+
534545
class DirectoryTestCase(ASTTestCase):
535546
"""Test roundtrip behaviour on all files in Lib and Lib/test."""
536547

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
:func:`ast.unparse` now doesn't use redundant spaces to separate ``lambda``
2+
and the ``:`` if there are no parameters.

0 commit comments

Comments
 (0)