Python Lambda WTF

Status
Not open for further replies.

kbogert

Smack-Fu Master, in training
77
Came across this today (code distilled down so I could post it):

Code:
t = []


for i in range(3):
        t.append(lambda : i)


t2  = []

def WTF(i):
        t2.append(lambda : i)


for i in range(3):
        WTF(i)


for x in t:
        print(x())

for x in t2:
        print(x())

This outputs:
Code:
2
2
2
0
1
2

WTF? It though the scope of the lambda is a snapshot of wherever it was created. Is there a way to get around this without having to add the function call?

Thanks in advance,
kdb
 

technophile

Ars Legatus Legionis
23,768
kbogert":80o1cww4 said:
WTF? It though the scope of the lambda is a snapshot of wherever it was created.
It is. Where this trips most people up is that it captures the scope, not the values. As you've discovered, this means that updating the value of a variable that is referenced in a closure actually updates the value for the closure as well. As you've also discovered, the workaround is to make a copy of the value locally and use the local instead of the capture. :)
 
Status
Not open for further replies.