Fear and suspicion of lambdas, was Re: Meta decorator with parameters, defined in explicit functions

Peter Otten __peter__ at web.de
Thu Jun 30 03:25:20 EDT 2016


Lawrence D’Oliveiro wrote:

> On Tuesday, June 28, 2016 at 5:03:08 PM UTC+12, Ben Finney wrote:
> 
>> I would like to see a more Pythonic, more explicit and expressive
>> replacement with its component parts easily understood.
> 
> I don’t know why this fear and suspicion of lambdas is so widespread among
> Python users ... former Java/C# programmers, perhaps?

If there is "fear" I don't share it. However, for

foo = lambda <args>: <expr>

there is syntactic sugar in Python that allows you to write it as

def foo(<args>):
    return <expr>

with the nice side effects that it improves the readability of tracebacks 
and allows you to provide a docstring.

So yes, assigning a lambda to a name raises my "suspicion".

If a lambda is provided as an argument or as part of an expression I wonder 
how it is tested, and if even if it is trivial like

def reduce(items, func=lambda x, y: x + y): ...

the alternative

def reduce(items, func=add): ...

looks more readable in my eyes even though somewhere -- under the rug or in 
the operator module -- you need

def add(x, y):
   """
   >>> add(3, 4)
   7
   """
   return x + y

>>     decorator_with_args = lambda decorator: lambda *args, **kwargs: 
lambda func: decorator(func, *args, **kwargs)
> 
> Ah, I see why there are 3 lambdas, instead of 2. It’s so that you can 
write

I have a suspicion that there would not have been a correction "I see why 
there are three functions instead of two" ;)




More information about the Python-list mailing list