python-guide
python-guide copied to clipboard
Tip on the "Late Binding Closures" section
The two solutions in "What You Should Do Instead" are certainly correct, while there's another solution in that special case, one can simply change
return [lambda x : i * x for i in range(5)]
to
return (lambda x : i * x for i in range(5))
in other words, one can create a generator, rather than a list, to postpone the time when cell contents be evaluated. Actually, a more essential test code could be
for multiplier in create_multipliers():
print multiplier.__closure__[0].cell_contents
FYI.