Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions Lib/ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -716,9 +716,9 @@ def fill(self, text=""):
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):
Expand Down Expand Up @@ -1566,8 +1566,11 @@ def visit_keyword(self, node):

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)
Expand Down
11 changes: 11 additions & 0 deletions Lib/test/test_unparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -531,6 +531,17 @@ def test_slices(self):
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."""

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