software-mariodiana
3/2/2016 - 4:33 PM

A rough implementation of the Cocoa framework's delegate pattern in Python. (The examples are a bit contrived.)

A rough implementation of the Cocoa framework's delegate pattern in Python. (The examples are a bit contrived.)

def try_delegate(f):
    """
    Decorator function to allow a delegate object to execute the message, if able.
    """
    def is_delegate_function_implemented(obj, func):
        return (hasattr(obj, 'delegate') and 
                hasattr(obj.delegate, func.__name__) and 
                callable(getattr(obj.delegate, func.__name__)))

    def wrapper(*args, **kwargs):
        me = args[0]
        if is_delegate_function_implemented(me, f):
            if len(args) > 1:
                params = args[1: ]
                return getattr(me.delegate, f.__name__)(*params, **kwargs)
            else:
                return getattr(me.delegate, f.__name__)(**kwargs)
        else:
            return f(*args, **kwargs)

    return wrapper


#=================
# Usage examples.
#=================

class Boss(object):
    @try_delegate
    def doStuff(self):
        print "foo"

    @try_delegate
    def sayHello(self, name):
        print "Hello, %s!" % (name)

    @try_delegate
    def showFriend(self, first="John", last="Doe"):
        print "Hello, %s %s!" % (first, last)


class Flunky(object):
    def doStuff(self):
        print "bar"

    def sayHello(self, name):
        print "Bonjour, %s!" % (name)

    def showFriend(self, first="Jane", last="Smith"):
        print "Bonjour, %s %s!" % (first, last)



b = Boss()
b.doStuff()
b.sayHello("World")
b.showFriend()

print

b.delegate = Flunky()
b.doStuff()
b.sayHello("World")
b.showFriend()