Middle
What is a closure in Python?
sobes.tech AI
Answer from AI
A closure is a function that remembers the values from its surrounding scope even after that scope no longer exists.
Key features:
- Nested function: A closure occurs when a function is defined inside another function.
- Access to outer variables: The nested function accesses one or more variables from its containing outer function.
- Preservation of state: The values of these outer variables are preserved in the closure after the outer function has finished executing.
Example:
def outer_function(x):
def inner_function(y):
return x + y # inner_function uses the variable x from outer_function
return inner_function
# Creating a closure by passing a value for x
closure_add_five = outer_function(5)
# Calling the closure with a value for y
result = closure_add_five(3)
# The variable x (with value 5) is stored in closure_add_five
In this example, inner_function is a closure. It "remembers" the value of the variable x (which was 5 at the time outer_function was called), even after outer_function has finished. When calling closure_add_five(3), the closure uses the stored value x=5 and computes 5 + 3.
Uses of closures:
- Implementation of decorators.
- Partial application of functions.
- Creating functional objects with preserved state.