mirror of
https://github.com/python/cpython.git
synced 2025-09-26 18:29:57 +00:00
bpo-44081: improve ast.unparse() for lambdas with no parameters (GH-26000)
This commit is contained in:
parent
4aa63d65a9
commit
e4e931a67e
3 changed files with 21 additions and 5 deletions
|
@ -716,9 +716,9 @@ class _Unparser(NodeVisitor):
|
||||||
self.maybe_newline()
|
self.maybe_newline()
|
||||||
self.write(" " * self._indent + text)
|
self.write(" " * self._indent + text)
|
||||||
|
|
||||||
def write(self, text):
|
def write(self, *text):
|
||||||
"""Append a piece of text"""
|
"""Add new source parts"""
|
||||||
self._source.append(text)
|
self._source.extend(text)
|
||||||
|
|
||||||
@contextmanager
|
@contextmanager
|
||||||
def buffered(self, buffer = None):
|
def buffered(self, buffer = None):
|
||||||
|
@ -1567,7 +1567,10 @@ class _Unparser(NodeVisitor):
|
||||||
def visit_Lambda(self, node):
|
def visit_Lambda(self, node):
|
||||||
with self.require_parens(_Precedence.TEST, node):
|
with self.require_parens(_Precedence.TEST, node):
|
||||||
self.write("lambda")
|
self.write("lambda")
|
||||||
|
with self.buffered() as buffer:
|
||||||
self.traverse(node.args)
|
self.traverse(node.args)
|
||||||
|
if buffer:
|
||||||
|
self.write(" ", *buffer)
|
||||||
self.write(": ")
|
self.write(": ")
|
||||||
self.set_precedence(_Precedence.TEST, node.body)
|
self.set_precedence(_Precedence.TEST, node.body)
|
||||||
self.traverse(node.body)
|
self.traverse(node.body)
|
||||||
|
|
|
@ -531,6 +531,17 @@ class CosmeticTestCase(ASTTestCase):
|
||||||
self.check_src_roundtrip("a[1, 2]")
|
self.check_src_roundtrip("a[1, 2]")
|
||||||
self.check_src_roundtrip("a[(1, *a)]")
|
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):
|
class DirectoryTestCase(ASTTestCase):
|
||||||
"""Test roundtrip behaviour on all files in Lib and Lib/test."""
|
"""Test roundtrip behaviour on all files in Lib and Lib/test."""
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,2 @@
|
||||||
|
:func:`ast.unparse` now doesn't use redundant spaces to separate ``lambda``
|
||||||
|
and the ``:`` if there are no parameters.
|
Loading…
Add table
Add a link
Reference in a new issue