Senior
Tell about closures in Python. How does a function inside a function use variables from the outer function?
sobes.tech AI
Answer from AI
In Python, a closure is a function that remembers and can use variables from the scope of the outer function even after the outer function has finished executing.
When a function is defined inside another function, the inner function can access the variables of the outer function. These variables are stored in a special object called a closure.
Example:
def outer(x):
y = 10
def inner(z):
return x + y + z # Uses variables from the outer function
return inner
f = outer(5)
print(f(3)) # Outputs 18 (5 + 10 + 3)
Here, inner is a closure that 'captures' the variables x and y from outer. Even after outer has returned inner, these variables remain accessible inside inner.