I have a following simple code:
def get():
return [lambda: i for i in [1, 2, 3]]
for f in get():
print(f())
As expected from my python knowledge, output is 3 – entire list will contain last value of i. But how this works internally?
AFAIK, python variables are simply reference to objects, so first closure must enclose object first i reference – and this object is definitely 1, not 3 O_O. How it happens that python closure encloses variable itself instead of object this variable reference? Does it save variable name as plain text, some “reference to variable” or what?
Closures don’t refer to variables but rather to scopes. Since the last value of
iin its scope is ‘3’, all three closures return the same. To “lock” the current value of a variable, create a new scope just for it: