Posted by Pete McBreen 10 Dec 2010 at 21:55
Had a need to look at Python textbook recently and got confused several times by the examples that were needlessly obfuscated (slightly paraphrased code):
>>> def actions(): ... acts =  ... for i in range(5): ... acts.append(lambda x, i=i: i **x) ... return acts ... >>> acts = actions() >>> acts(2) 9
- For a newbie, it would not be obvious that
actsinside the function is NOT the same variable as the same variable
actsoutside of the function.
i=iis designed to be confusing, the first one is a new name in the scope of the lambda, the second is from the
forloop. The first should have had a different name to make it obvious what was happening.
- The name of the function
actionsjust does not communicate anything.
I’m going to have to think on this more, but maybe my next project is going to involve creating some material for newbies.