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

Steven D'Aprano steve at pearwood.info
Sat Dec 14 11:12:20 CET 2013


On Sat, Dec 14, 2013 at 09:27:17AM +0000, 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. 

No. But <lambda> *including the angle brackets* is the name of the 
function:

py> (lambda x: x).__name__
'<lambda>'




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

Remember that there are two meanings to "name" in Python:

1) names as in name bindings or variables:

   x = 42

   binds the value 42 to the name "x"


2) certain objects, such as classes, functions and modules, have 
   their very own name, which is not necessarily the same as the
   name the object is bound to:

py> import math as flibbert
py> flibbert.__name__
'math'


A function's personal name and the name it is bound to will initially be 
the same when using def, but not with lambda. We normally say that 
lambda functions are "anonymous", but they actually do have a name, it 
just happens to be the same name as every other function generated with 
lambda.



-- 
Steven


More information about the Tutor mailing list