Junior — Middle
Can you explain what a closure is and how it functions in the Python language?
sobes.tech AI
Answer from AI
In Python, a closure is a function that remembers and can use variables from the scope in which it was created, even if that scope is no longer active.
Example:
def outer():
x = 10
def inner():
return x + 5
return inner
func = outer()
print(func()) # Outputs 15
Here, inner is a closure that "closes over" the variable x from the outer function outer. Even after outer has finished executing, inner retains access to x.
This is useful for creating functions with preserved state without using global variables.