The Late Binding Trap
What does this code print?
def create_multipliers():
multipliers = []
for i in range(1, 4):
def multiply(x):
return x * i
multipliers.append(multiply)
return multipliers
funcs = create_multipliers()
result = sum(f(2) for f in funcs)
print(result)All three functions share the same variable i, not its value at creation time.
Comments
Loading the conversation…