Python: Callbacks, Delegates, ... ? What is common? Python: Callbacks, Delegates, ... ? What is common? python python

Python: Callbacks, Delegates, ... ? What is common?


Personally I don't see a difference between callbacks, listeners, and delegates.

The observer pattern (a.k.a listeners, a.k.a "multiple callbacks") is easy to implement - just hold a list of observers, and add or remove callables from it. These callables can be functions, bound methods, or classes with the __call__ magic method. All you have to do is define the interface you expect from these - e.g. do they receive any parameters.

class Foo(object):  def __init__(self):    self._bar_observers = []  def add_bar_observer(self, observer):    self._bar_observers.append(observer)  def notify_bar(self, param):    for observer in self._bar_observers:      observer(param)def observer(param):  print "observer(%s)" % paramclass Baz(object):  def observer(self, param):    print "Baz.observer(%s)" % paramclass CallableClass(object):  def __call__(self, param):    print "CallableClass.__call__(%s)" % parambaz = Baz()foo = Foo()foo.add_bar_observer(observer) # functionfoo.add_bar_observer(baz.observer) # bound methodfoo.add_bar_observer(CallableClass()) # callable instancefoo.notify_bar(3)


I can't speak for common approaches, but this page (actual copy is unavailable) has an implementation of the observer pattern that I like.

Here's the Internet Archive link:http://web.archive.org/web/20060612061259/http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html


It all depends on the level of complexity your application requires. For simple events, callbacks will probably do. For more complex patterns and decoupled levels you should use some kind of a publish-subscribe implementation, such as PyDispatcher or wxPython's pubsub.

See also this discussion.