VocalBit« assorted thoughts on technology, computers and programming »

An alternative lambda syntax for Python

A syntax proposal for Python that would replace the use of lambdas as function keyword values.


I don't use lambdas often. But when I do, they are usually an argument to a function such as:

lst.sort(key=lambda user:user.name)

I find the lambda syntax cumbersome to read and write. I think the concept is easy to understand but the syntax sticks out like a sore thumb in a clean language like Python.

Python almost lost lambdas in 3.0, GvR said:

once map(), filter() and reduce() are gone, there aren't a whole lot of places where you really need to write very short local functions

Sure enough - when I look through my code, lambdas are exclusively used within function calls, as values for keyword argument (and the bulk of them in list.sort()).


I propose a shorter and clearer way to express lambdas as keyword arguments. Instead of writing:

lst.sort(key=lambda user:user.name)

You would write:


By writing parenthesis to the left of the '=', you specify that you are defining a nested function. The arguments to this 'inline function' are defined in the parenthesis to the left of the equal sign. The scope of this function exists between the equal sign and the comma (or closing parenthesis). Note that this eliminates the lambda keyword entirely. The parenthesis before the '=' make this syntax unambiguous.

You can use this syntax only with a named keyword argument. This means it won't work in a standalone assignment statement or anywhere outside a function call - I believe this is a good thing and covers most (if not all) cases where lambda might be used.

A big advantage is that it can be read as you might read mathematical notation: "key of user is user.name". A downside might be that when a beginner encounters this, he/she may not know how to search the documentation for this construct.

What do you think?


(Almost) all lambda alternatives ever proposed
Guido van Rossum's pronouncement to 'just keep lambda'
Guido van Rossum's original blog about functional programming in Python