Closure Use Cases
Practical Applications of Closures
graph TD
A[Closure Use Cases] --> B[Function Decorators]
A --> C[Callback Implementations]
A --> D[State Management]
A --> E[Data Encapsulation]
1. Function Decorators
Simple Decorator Example
def timer_decorator(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"Function {func.__name__} took {end - start} seconds")
return result
return wrapper
@timer_decorator
def slow_function():
import time
time.sleep(2)
print("Slow function completed")
slow_function()
2. Callback and Event Handling
def event_handler(event_type):
def handler(callback):
def wrapper(*args, **kwargs):
print(f"Handling {event_type} event")
return callback(*args, **kwargs)
return wrapper
return handler
@event_handler("user_login")
def login_process(username):
print(f"Logging in user: {username}")
login_process("john_doe")
3. Configuration and Parameterization
Use Case |
Description |
Example |
Configuration |
Create configured functions |
Database connection |
Parameterization |
Generate specialized functions |
Logging levels |
Configuration Closure
def database_connector(host):
def connect(username, password):
## Simulated database connection
print(f"Connecting to {host} with {username}")
return f"Connection to {host} established"
return connect
mysql_connector = database_connector("localhost")
connection = mysql_connector("admin", "secret")
4. State Management Without Classes
def counter(initial=0):
count = [initial]
def increment():
count[0] += 1
return count[0]
def decrement():
count[0] -= 1
return count[0]
return increment, decrement
inc, dec = counter(10)
print(inc()) ## 11
print(dec()) ## 10
5. Data Encapsulation
def secure_data_storage():
data = {}
def store(key, value):
data[key] = value
def retrieve(key):
return data.get(key, None)
return store, retrieve
save, get = secure_data_storage()
save("username", "labex_user")
print(get("username")) ## labex_user
Advanced Use Cases
Partial Function Application
def multiply(x, y):
return x * y
def partial(func, x):
def wrapper(y):
return func(x, y)
return wrapper
double = partial(multiply, 2)
print(double(5)) ## 10
Best Practices
- Use closures for lightweight state management
- Prefer closures over global variables
- Be cautious of memory overhead
- Leverage closures for functional programming patterns
At LabEx, we emphasize using closures to create more modular, flexible, and maintainable Python code that follows functional programming principles.