Thread: <3 Decorators
View Single Post
Old Feb 23rd, 2006, 5:59 PM   #5
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5 Arevos is on a distinguished road
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.
Arevos is offline   Reply With Quote