Junior — Middle
Can you explain what happens inside a closure function and how it remembers surrounding variables?
sobes.tech AI
Answer from AI
A closure in Python is a function that remembers and can use variables from its surrounding (outer) context, even after that context has finished execution.
When a nested function is defined inside another function, it captures references to variables from the outer function, not their values. These variables are stored in a special memory area called a closure, which allows the nested function to access them later.
Example:
def outer(x):
def inner(y):
return x + y # x is taken from the outer function
return inner
f = outer(10)
print(f(5)) # Outputs 15
Here, inner remembers the value of x from outer, even after outer has finished. This allows creating functions with preserved state without using global variables.