[lambda]Is the behavior expected?

Diez B. Roggisch deets at nospam.web.de
Wed Nov 26 07:48:00 EST 2008


Alphones wrote:

> Hi all,
> 
> 
> def getFunc(x):
>     return lambda y : x + y
> 
> if __name__ == '__main__':
>     todo = []
>     proc = getFunc(1)
>     todo.append(lambda: proc(1))
>     proc = getFunc(2)
>     todo.append(lambda: proc(1))
>     proc = getFunc(3)
>     todo.append(lambda: proc(1))
> 
>     todo.append(lambda: getFunc(1)(1))
>     todo.append(lambda: getFunc(2)(1))
>     todo.append(lambda: getFunc(3)(1))
> 
>     for task in todo:
>         print task()
> 
> -----------
> the program outputs:
> 4
> 4
> 4
> 2
> 3
> 4
> in Python 2.6.
> is that excpected?

Yes. Creating a lambda will close over the current *names* in the scope,
*not* their respective values. For that, you need to create a new scope -
e.g. by bindig the value to a argument of the lambda:

lambdas = []
for i in xrange(10):
    lambda i=i : i ** 2

for l in lambdas:
    l()

Diez
   



More information about the Python-list mailing list