Closure Functions in Python
Closure Functions in Python
A closure is a function that remembers values from its enclosing lexical scope even when the program flow is no longer in that scope.
Simple Example
python
def outer_function(x):
# This is the enclosing scope
def inner_function(y):
# inner_function can access 'x' from outer_function's scope
return x + y
return inner_function # Return the inner function itself
# Create closures
add_five = outer_function(5)
add_ten = outer_function(10)
# Use the closures
print(add_five(3)) # Output: 8 (5 + 3)
print(add_five(7)) # Output: 12 (5 + 7)
print(add_ten(3)) # Output: 13 (10 + 3)
Key Characteristics of Closures
- Nested Function: A function defined inside another function
- Access to Enclosing Scope: The inner function can access variables from the outer function
- Returning the Function: The outer function returns the inner function
Practical Example: Counter
python
def make_counter():
count = 0 # This variable is "remembered" by the closure
def counter():
nonlocal count # Allows modifying the variable from outer scope
count += 1
return count
return counter
# Create counter instances
counter1 = make_counter()
counter2 = make_counter()
print(counter1()) # Output: 1
print(counter1()) # Output: 2
print(counter2()) # Output: 1 (separate instance)
print(counter1()) # Output: 3
Another Example: Custom Greeting
python
def create_greeting(greeting_word):
def greet(name):
return f"{greeting_word}, {name}!"
return greet
say_hello = create_greeting("Hello")
say_hi = create_greeting("Hi")
print(say_hello("Alice")) # Output: Hello, Alice!
print(say_hi("Bob")) # Output: Hi, Bob!
Why Use Closures?
- Data Encapsulation: Hide implementation details while maintaining state
- Function Factories: Create specialized functions from a template
- Callback Functions: Useful in event-driven programming
- Decorators: Closures are the foundation of Python decorators
Closures are powerful because they allow functions to “remember” their context, making them more flexible and reusable.