[Tutor] weird lambda expression -- can someone help me understand how this works

Peter Otten __peter__ at web.de
Sat Dec 14 10:49:12 CET 2013


Alan Gauld wrote:

> On 14/12/13 04:19, Steven D'Aprano wrote:
> 
>> Lambda is just syntactic sugar for a function. It is exactly the same as
>> a def function, except with two limitations:
>>
>> - there is no name, or to be precise, the name of all lambda functions
>> is the same, "<lambda>";
> 
> Sorry, I don't think that is precise. lambda is not the name of the
> function. You can't use lambda to access the function(s) or treat it
> like any other kind of name in Python. In fact if you try to use it as a
> name you'll likely get a syntax error.
> 
> lambda is the key word that defines the function. But its no more
> the name of the function than def is.

There is the (variable) name the function object is bound to and the 
function's __name__ attribute. In the example below "<lambda>" is the 
__name__ while the function object is bound to the name "f":

>>> f = lambda x: math.sqrt(x) + f(x-1)
>>> f.__name__
'<lambda>'
>>> f(5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
  File "<stdin>", line 1, in <lambda>
  File "<stdin>", line 1, in <lambda>
  File "<stdin>", line 1, in <lambda>
  File "<stdin>", line 1, in <lambda>
  File "<stdin>", line 1, in <lambda>
  File "<stdin>", line 1, in <lambda>
ValueError: math domain error


When the normal way to define a function object is used both __name__ 
attribute and variable name are identical (at least initially):

>>> def f(x): return math.sqrt(x) + f(x-1)
... 
>>> f.__name__
'f'
>>> f(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in f
  File "<stdin>", line 1, in f
  File "<stdin>", line 1, in f
  File "<stdin>", line 1, in f
ValueError: math domain error




More information about the Tutor mailing list