[Python-ideas] a new lambda syntax

Steven D'Aprano steve at pearwood.info
Tue Oct 20 01:06:29 CEST 2009

On Tue, 20 Oct 2009 01:04:47 am Oleg Broytman wrote:
> On Mon, Oct 19, 2009 at 09:33:06PM +0800, starwing wrote:
> > current lambda only support single line
> > syntax. it's not very good.
>    This is where you've made an error. Single-line lambdas are good
> enough, and if you need more - just create a named function.
> Oleg.

Actually, lambda isn't limited to a single line, but to a single 
expression, and expressions can go over multiple lines:

>>> data = [1, 2, 3, 4]
>>> map(lambda n: (
...   n**3 -  # comment goes here
...   n**2 +
...   n + 1), data)
[2, 7, 22, 53]


The only limitation is that the lambda syntax is limited to a single 
expression, which means you can't call statements.

If your "anonymous code block" is more complicated than a single short 
expression, it's too complicated to be "obviously correct" just from 
looking at it, and so it should be documented and tested. The 
restriction on lambda forces people to move the code block into a named 
function, which has the happy consequence of encouraging documentation 
and testing.

Steven D'Aprano

More information about the Python-ideas mailing list