Understanding Python Closure Late Binding and How to Fix It
This article explains Python's closure late-binding behavior that causes unexpected lambda results, demonstrates the issue with a sample interview question, and presents four practical solutions—including default‑argument binding, functools.partial, generator expressions, and yield‑based lazy evaluation—to achieve the intended outputs.
The post discusses a common Python interview question that reveals the pitfalls of late binding in closures, where lambdas capture the loop variable by reference, leading to unexpected results.
Problematic code:
def testFun():
temp = [lambda x : i*x for i in range(4)]
return temp
for everyLambda in testFun():
print(everyLambda(2))Running this prints 6 four times because the loop finishes with i = 3 , and each lambda uses that final value when called.
Solution 1 – bind the current value using a default argument:
def testFun():
temp = [lambda x, i=i: i * x for i in range(4)]
return temp
for everyLambda in testFun():
print(everyLambda(2))Solution 2 – use functools.partial to fix the argument:
from functools import partial
from operator import mul
def testFun():
return [partial(mul, i) for i in range(4)]
for everyLambda in testFun():
print(everyLambda(2))Solution 3 – employ a generator expression with the same default‑argument trick:
def testFun():
return (lambda x, i=i: i * x for i in range(4))
for everyLambda in testFun():
print(everyLambda(2))Solution 4 – use a lazy‑evaluated generator with yield :
def testFun():
for i in range(4):
yield lambda x: i * x
for everyLambda in testFun():
print(everyLambda(2))All four approaches produce the expected output 0 2 4 6 (or printed line by line), demonstrating how to avoid the late‑binding trap in Python closures.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.