What are closures in Python?
A closure in Python is a technique where an inner function remembers and has access to variables from its enclosing scope even after the outer function has finished executing.
What is a Closure?
In Python, a closure is a nested function that 'remembers' the environment in which it was created, specifically the values of variables from its enclosing (outer) scope, even after the outer function has completed its execution. For a closure to exist, three conditions must be met: there must be a nested function, the nested function must refer to a variable from its enclosing scope, and the outer function must return the nested function.
How Do Closures Work?
When an outer function is called and it returns an inner function, the inner function doesn't just return; it carries with it a reference to the outer function's execution environment (its scope). This means that any non-local variables that the inner function referenced are 'closed over' and remain accessible to the inner function, even if the outer function's stack frame has been popped.
Example of a Closure
def make_adder(x):
def adder(y):
return x + y
return adder
# Create two adder functions, each remembering a different 'x'
add_5 = make_adder(5)
add_10 = make_adder(10)
# Use the created adder functions
print(add_5(3)) # Output: 8 (5 + 3)
print(add_10(7)) # Output: 17 (10 + 7)
In this example, make_adder is the outer function, and adder is the inner (nested) function. When make_adder(5) is called, it returns the adder function. This returned adder function 'remembers' that x was 5 from its enclosing scope. Similarly, when make_adder(10) is called, the new adder function remembers x as 10. Each adder instance (add_5 and add_10) has its own independent x value maintained by the closure.
Why Use Closures?
- Data Encapsulation: Closures can be used to hide data and implement private variables, similar to objects in object-oriented programming.
- Function Factories: They are excellent for creating functions dynamically based on some input parameters, as shown in the
make_adderexample. - Decorators: Python decorators are a prominent application of closures, where one function wraps another to extend its functionality without modifying its code.
- Maintaining State: In functional programming, closures can be used to maintain state across multiple calls to a function without resorting to classes or global variables.