3 ms·
Sometimes, I just want to pass a function to a function. And sometimes, I want to just say, very concisely, "do this", without giving a name to "this".
by bkovitz 18y ago
Sometimes, I just want to pass a function to a function. And sometimes, I want to just say, very concisely, "do this", without giving a name to "this".
- schtog 18y agoBut you can do that in both python 3 and 2.5...
- kilowatt 18y agoMaybe he's talking about >>> funcs = [] >>> for x in xrange(3): >>> funcs.append(lambda: x) >>> sum(f() for f in funcs) 6 Were you expecting 3? Lambdas (besides having such an awfully long and difficult to type name :P) capture only the "name" of x, so when the for loop changes x later, the lambda sees the new value--so the sum is (2 + 2 + 2) instead of (1 + 2 + 3). What you can do, instead (and I do it often enough that I wish lambdas created their own lexical closure....) >>> funcs = [] >>> for x in xrange(3): >>> funcs.append(lambda x=x: x) >>> sum(f() for f in funcs) 3 By using x as a default argument, you force the x inside the lambda to be the value it was when the lambda was created. It kinda sucks, and always felt to me like a deficiency of the implementation leaking up into the language :[
- matstc 18y agoI think you mean "2 + 2 + 2 instead of 0 + 1 + 2"