3 ms·
It took me a minute to see the problems, but - not having touched Python for over a decade - I can't for the life of me bring the lambda to capture the value of
by dahauns 10y ago
It took me a minute to see the problems, but - not having touched Python for over a decade - I can't for the life of me bring the lambda to capture the value of the variable.
I know this doesn't work (because python assignment rules)
def foo(a, methods=[]):
m=[];
for bla in methods:
m.append(bla)
for i in range(3):
k = i
m.append(lambda x: x + k)
But this should work, according to quick'n'dirty google (because default assignment), and yet it doesn't.
for i in range(3):
def bar(c, d=i): return c+d
m.append(lambda x: bar(x))
EDIT:
Ok, I'm something missing here.
This doesn't capture the value of i
for i in range(3):
m.append(lambda x,i=i: x+i)
But this does. WTH?!
for i in range(3):
m.append(lambda i=i: i)
- flavianh 10y agoThat's an interesting try! I think the default assignment is done by reference as well, so when i changes in the loop the default value changes as well? Similarly to methods=[]. Can't say for sure though. The solution I give in the article is the only one I could come up with, I'm interested if you find another one :)
- dahauns 10y agoAh - the answer was so simple: I'm an idiot. for i in range(3): m.append(lambda x,i=i: x+i) actually works, I just had a brain fart. :)