Why I hate lambdas (Re: Do any of you recommend Python as a first programming language?)

Roy Smith roy at panix.com
Sun Mar 23 13:51:34 EDT 2008


> Also, despite reassurances to the contrary, I still get the impression 
> that there is a strong anti-lambda sentiment among the Python "in" 
> crowd.  Is it just a question of the word "lambda," as opposed to 
> perceived cleaner syntax?

There is a fundamental disharmony in how functions and other objects are 
treated in Python.  If I say:

x = ['surprise', 'fear', 'ruthless efficiency']

I've done two things.  First, I've created a list, then I've bound the name 
x to that list (maybe "bound" is not exactly the right terminology).  Until 
the assignment happend, the list had no name.  In fact, it still has no 
name; there's just a reference to it stored in a variable whose name is x.  
If I were to then do

y = x

now y and x have equal relationships to the original list.  The list's name 
is no more x than it is y, since the whole concept of "the name of the 
list" doesn't have any meaning in Python.

On the other hand, when I do:

def torture():
    woman.putInChair()
    cushion.poke()
    rack.turn()

I've also done two things.  First, I've created a function object (i.e. a 
lambda body), and I've also bound the name torture to that function object, 
in much the same way I did with the list.  But, it's different.  The 
function object KNOWS that it's name is torture.  When I later reassign it 
to another name and run it:

weapon = torture
weapon()

This is what I get:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in torture
NameError: global name 'woman' is not defined

Notice, the second line in the stack trace identified the function's name 
as "torture", not "weapon".  Because that IS the function's name.  Lists 
are anonymous.  Functions have names (as do a few other things like classes 
and modules).  If I ask a list what its name is, I get:

AttributeError: 'list' object has no attribute '__name__'

but, if I ask a function what it's name is (regardless of what name I've 
bound it to), I get the right answer:

>>> torture.__name__
'torture'
>>> weapon.__name__
'torture'
>>> 

If we created lisp-like lambdas and bound them to names like we did with 
other types of objects, we wouldn't have that.

What Python give us with lambdas is some half-way thing.  It's not a full 
function, so it's something that people use rarely, which means most people 
(like me) can't remember the exact syntax.  Even when I know it's the right 
thing to be using in a situation, I tend not to use it simply because the 
path of least resistance is to write a one-off function vs. looking up the 
exact syntax for a lambda in the manual.



More information about the Python-list mailing list