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

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Mon Mar 24 00:48:29 EDT 2008


On Sun, 23 Mar 2008 22:36:35 -0400, Roy Smith wrote:

>> > 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.
>> 
>> No it does not. Function objects don't know their name. All they know
>> is that they have a label attached to them that is useful to use as a
>> name in some contexts, e.g. when printing tracebacks. It's just a
>> label, nothing more.
> 
> I think we're arguing the same thing.  When you write
> 
> def foo():
>    whatever
> 
> you create an object which contains the string "foo", retrievable
> through its __name__ attribute.  That's what I meant by "it knows its
> name"


But that's not true. Firstly, you can't access the __name__ attribute 
unless you already have a reference to the object (not necessarily a 
name), so clearly the __name__ attribute isn't how you retrieve objects.

Secondly, the __name__ attribute has no special purpose. It's not even 
used for tracebacks.


>>> def foo():
...     return "result"
...
>>> foo.__name__ = "something"
>>> something()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'something' is not defined
>>> 
>>> something = foo
>>> something()
'result'
>>> something(None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() takes no arguments (1 given)
>>> something.__name__
'something'


-- 
Steven



More information about the Python-list mailing list