lambda functions ?

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Mon Feb 5 18:13:43 EST 2007


Maxim Veksler a écrit :
> Hello,
> I'm new on this list and in python.

Welcome on board...

> It seems python has some interesting concept of "ad hoc" function
> which I'm trying to understand without much success.
> 
> Take the following code for example:
> 
> """
> 
>>>> def make_incrementor(n):
> 
> ... return lambda x: x + n
> ...
> 
>>>> f = make_incrementor(42)
>>>> f(0)
> 
> 42
> 
>>>> f(1)
> 
> 43
> """
> 
> I really don't understand whats going on here.
> On the first instantiating of the object "f" where does "x" gets it's
> value?

Nowhere. The above code is strictly equivalent to:

def make_incrementor(n):
   def inc(x):
     return x + n
   return inc

It's based on the fact that (for short):
1/ Python functions are first-class objects, and as such can be passed 
around just like any other object
2/ Python functions are closures, meaning they carry the environment in 
which they where defined.

IOW, make_incrementor(n) creates and returns a new function each time 
it's called. This function remembers the value of n with which it was 
created, and just awaits to be called with the missing x arg.

  Or is it evaluated as 0? ie "x: 0 + 42"
> 
> And what is the "f" object? An integer? a pointer? an Object?

an object, instance of class function.

> I'm coming from the C world...
> 
> Could some please try (if even possible) to implement the above code
> without using "lambda" I believe it would help me grasp this a bit
> faster then.

cf above.

FWIW, lambda is just a syntactic sugar for creating anonymous, 
dead-simple functions, usually used as callbacks for generic functions 
or methods like map, filter, list.sort etc.

FWIW(2), this programming style (anonymous functions, closures etc) 
comes from functional programming (Haskell, ML, lisp, etc...).

> Thank you,

HTH



More information about the Python-list mailing list