alixi6
alixi6

Reputation: 11

When we use a for loop to create functions - is it a closure?

I'm trying to get across the concept of closure in Python. I have seen many examples like that:

funcs = []
for n in range(1, 4):
    funcs.append(lambda x: x + n)

for f in funcs:
    print(f(1))

I get why the output is: 4 4 4

But what I can't understand is why this is called a closure at all? Isn't closure supposed to be a nested function that has access to the variables of the enclosing function? While here we just modify a global varible n which equals 3 after the last cycle.

What is more, if you assign a variable for a function

a = funcs[1]
print(a.__closure__)
print(a.__code__.co_freevars)

It returnes

None
()

So tell me please, does the code above creates a closure or doesn't? Should I think of n as a free variable in closure or just a global variable?

Upvotes: 1

Views: 130

Answers (0)

Related Questions