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[3](2)
9
- For a newbie, it would not be obvious that
acts
inside the function is NOT the same variable as the same variableacts
outside of the function. - The
i=i
is designed to be confusing, the first one is a new name in the scope of the lambda, the second is from thefor
loop. The first should have had a different name to make it obvious what was happening. - The name of the function
actions
just 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.