[Python-ideas] Thoughts on lambda expressions

Abe Dillon abedillon at gmail.com
Wed Mar 2 21:00:08 EST 2016



On Wednesday, March 2, 2016 at 7:10:37 PM UTC-6, Sjoerd Job Postmus wrote:
>
> So, I'm looking at my recipe book, and it first tells me which 
> ingredients I need, before telling me how to make the thing I want. 
>

Recipes are full of steps that could refer to other recipes but offer a 
more expressive form:

cream the butter and sugar together  # make cream from butter and sugar

caramelize the sugar  # make caramel from sugar

 Trying to apply the whole recipe metaphor to lambda expressions misses the 
point. Lambda expressions are expressive when their short and surrounded by 
context (like being the first argument to the 'map' function). They aren't 
comparable to a stand-alone recipe. It is possible to write arbitrary 
length programs in a lambda expression but that's not what they're meant 
for and it usually makes code more obfuscated than expressive.
 

>
> I also think your perception that the expression is more important than 
> the signature does not in general hold. After all, one writes 
>
>     def foo(bar, baz): 
>         <recipe> 
>
> instead of 
>
>     def: 
>         <recipe> 
>     as foo(bar, baz) 
>

Yes, that's because function definitions are different than lambda 
expressions and have a different use case. I'm not proposing that function 
definitions should follow the reverse syntax. Defined functions are usually 
abstracted away from any particular context while lambdas only make sense 
in very specific contexts.
 

>
> Furthermore, regarding simple lambdas---as in 
>
>     lambda x: <expression with x> 
>
> The extra reading of `lambda x` is not that problematic.


It isn't *that* problematic, but it is noise. It could be better. That's 
what I'm proposing.
 

> However, when 
> you have a lambda needing multiple parameters---as in 
>
>     lambda param1, param2, param3=default: <expression> 
>
> I think the order of the parameters and such is even more important, 
> because it is an easy thing to have in the wrong order. 
>

Again, the use cases for lambdas with complex signatures are very rare. 
Your own investigation confirmed this:
 

> Just out of curiosity, I grepped over the lambdas I could find in my 
> (3.4) standard library. Of the 123 lambdas I found, only 12 of them have 
> more than 1 argument. 
> In most of these 12 cases, the only reason for the many arguments is to 
> capture the value of a variable inside a loop, to make sure it uses the 
> relevant version of that variable (and/or faster lookop). 
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160302/a83beab0/attachment.html>


More information about the Python-ideas mailing list