python-guide icon indicating copy to clipboard operation
python-guide copied to clipboard

Tip on the "Late Binding Closures" section

Open borzhang opened this issue 9 years ago • 0 comments

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.

borzhang avatar Mar 16 '15 14:03 borzhang