Multimethods spring to mind as one good use for decorators, and since a while ago we were talking about thread,
here's a decorator that mimics the synchronized keyword in Java. I also find decorators quite useful for event based programming:
event_registry = {}
def listen_for(event_class):
if event_registry.has_key(event_class):
event_registry[event_class].append(func)
else:
event_registry[event_class] = [func]
def decorator(func):
def decorated(event):
return func(event)
return decorated
return decorator
def send_event(event):
if event_registry.has_key(event.__class__):
for func in event_registry[event.__class__]:
func(event)
class PokeEvent: pass
@listen_for(PokeEvent)
def poked(event):
print "Ouch!"
send_event(PokeEvent()) Although I'd probably opt for an
off-the-shelf dispatch system, rather than trying to reinvent the wheel, if I were programming a real application.