Callable Patterns
Decorator Pattern
Decorators are a powerful callable pattern that allows modifying or enhancing functions without changing their source code.
def timer_decorator(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end - start} seconds")
return result
return wrapper
@timer_decorator
def slow_function():
import time
time.sleep(2)
slow_function()
Callable Class Patterns
Strategy Pattern
class PaymentStrategy:
def pay(self, amount):
raise NotImplementedError()
class CreditCardPayment(PaymentStrategy):
def pay(self, amount):
print(f"Paying ${amount} with Credit Card")
class PayPalPayment(PaymentStrategy):
def pay(self, amount):
print(f"Paying ${amount} with PayPal")
class PaymentProcessor:
def __init__(self, strategy):
self.strategy = strategy
def process_payment(self, amount):
self.strategy.pay(amount)
## Usage
credit_payment = PaymentProcessor(CreditCardPayment())
credit_payment.process_payment(100)
Function Factory Pattern
def create_multiplier(factor):
def multiplier(x):
return x * factor
return multiplier
double = create_multiplier(2)
triple = create_multiplier(3)
print(double(5)) ## 10
print(triple(5)) ## 15
Callable Workflow
graph TD
A[Input] --> B{Callable Object}
B -->|Function| C[Execute Function]
B -->|Class Method| D[Call __call__ Method]
B -->|Decorator| E[Modify Function Behavior]
Common Callable Patterns
Pattern |
Description |
Use Case |
Decorator |
Modify function behavior |
Logging, timing, authentication |
Strategy |
Define a family of algorithms |
Payment processing, sorting |
Factory |
Create callable objects dynamically |
Configuration, plugin systems |
Context Manager Pattern
class FileHandler:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
self.file = None
def __call__(self):
self.file = open(self.filename, self.mode)
return self.file
def __enter__(self):
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
## Usage
with FileHandler('example.txt', 'w')() as f:
f.write('Hello, LabEx!')
Advanced Callback Mechanism
class EventManager:
def __init__(self):
self.callbacks = {}
def register(self, event_type, callback):
if event_type not in self.callbacks:
self.callbacks[event_type] = []
self.callbacks[event_type].append(callback)
def trigger(self, event_type, *args, **kwargs):
if event_type in self.callbacks:
for callback in self.callbacks[event_type]:
callback(*args, **kwargs)
## Example usage
def log_event(message):
print(f"Event logged: {message}")
def alert_event(message):
print(f"ALERT: {message}")
event_manager = EventManager()
event_manager.register('error', log_event)
event_manager.register('error', alert_event)
event_manager.trigger('error', 'System malfunction')
Key Takeaways
- Decorators modify function behavior
- Callable classes enable complex object interactions
- Function factories create dynamic callable objects
- Context managers provide advanced resource management
- Event systems leverage callable patterns for flexible communication