What is "lambda x=x : ... " ?

Fredrik Lundh fredrik at pythonware.com
Thu Jan 10 13:42:40 EST 2008


zslevi at gmail.com wrote:

> ####################
> Now, CPS would transform the baz function above into:
> 
> def baz(x,y,c):
>         mul(2,x,lambda v,y=y,c=c: add(v,y,c))
> 
> ###################
> 
> What does "y=y" and "c=c" mean in the lambda function?

they bind the argument "y" to the *object* currently referred to by the 
outer "y" variable.  for example,

     y = 10
     f = lambda y=y: return y
     y = 11

calling f() will return 10 no matter what the outer "y" is set to.

in contrast, if you do

     y = 10
     f = lambda: y
     y = 11

calling f() will return whatever "y" is set to at the time of the call.

or in other words, default arguments bind to values, free variables bind 
to names.

> I thought it bounds the outer variables, so I experimented a little
> bit:
> 
> #################
> x = 3
> y = lambda x=x : x+10
> 
> print y(2)
> ##################
> 
> It prints 12, so it doesn't bind the variable in the outer scope.

it does, but you're overriding the bound value by passing in a value.  try:

    x = 3
    y = lambda x=x : x+10
    y()
    x = 10
    y()

instead.

</F>




More information about the Python-list mailing list