[Python-ideas] Thoughts on lambda expressions

Sjoerd Job Postmus sjoerdjob at sjec.nl
Wed Mar 2 20:10:10 EST 2016


On Wed, Mar 02, 2016 at 04:19:42PM -0800, Abe Dillon wrote:
> 
> ...
> the idea is from the recipe metaphor for a function:
> 
> def <recipe>(<ingredients>):
>     ...instructions to cook ingredients
> 
> vs.
> 
>  (<make_something> from <ingredients>)
> 
> It's fair to quibble over the exact implementation (maybe use 'with' 
> instead of 'from') but the main point of the syntax it to put the important 
> bit (i.e.the expression) in front of the (usually) unimportant bit (i.e. 
> the signature) and to swap out an esoteric word (lambda) with something 
> that continues the readability emphasis of Python by using more common 
> words.
>  

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.

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)


Furthermore, regarding simple lambdas---as in 

    lambda x: <expression with x>

The extra reading of `lambda x` is not that problematic. 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.

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).


More information about the Python-ideas mailing list