lambda functions ?

Maxim Veksler hq4ever at gmail.com
Tue Feb 6 02:52:00 EST 2007


Wow,

Thank you everyone for the help. I am amazed by the motivation people
have on this list to help new comers. I hope that I will be able to
contribute equally some day.

On 05 Feb 2007 14:22:05 -0800, Paul Rubin
<"http://phr.cx"@nospam.invalid> wrote:
> "Maxim Veksler" <hq4ever at gmail.com> writes:
> > >>> def make_incrementor(n):
> > ... return lambda x: x + n
>
> Is the same as:
>
>   def make_incrementor(n):
>      def inner(x):
>         return x + n
>      return inner
>
> When you enter make_incrementor, it allocates a memory slot (normally
> we'd think of this as a stack slot since it's a function argument, but
> it's really in the heap) and copies its argument there.  Then you
> create the function "inner" which refers to that memory slot because
> of the reference to "n".  Then make_incrementor returns, but since the
> returned object still contains the reference to that memory slot, the
> memory slot is not freed (this is the part where it becomes important
> that the slot is really not on the stack).  So when you call the
> returned function, it still can get at that slot.
>

Following the debugger on your code, I can identify the following stages:

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

f = make_incrementor(10)
f(10)
f(0)

1. "def make_incrementor(n)" Create function object in memory and set
"make_incrementor" to point to it.
2. "f = make_incrementor(10)" Set "f" to point to "inner(x) function".
Set n value to 10.
3. "f(10)" Call to inner(x), which will return "father" n + "local" x.

This means that "f" is not a pointer to make_incrementor but rather to
the internal (copied?) function.

> This style is very common in Scheme programming so you might read a
> Scheme book if you want to understand it.  The classic:
>
>   http://mitpress.mit.edu/sicp/
>

I might just well do that.

> > 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.
>
> Does the above help?
all
Your explanation was excellent. Thank you.

> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
Cheers,
Maxim Veksler

"Free as in Freedom" - Do u GNU ?



More information about the Python-list mailing list