Skip to content

Instantly share code, notes, and snippets.

@alexlovelltroy
Created October 9, 2013 15:21
Show Gist options
  • Select an option

  • Save alexlovelltroy/6902984 to your computer and use it in GitHub Desktop.

Select an option

Save alexlovelltroy/6902984 to your computer and use it in GitHub Desktop.
This is a generic mixin that can add action handlers to any other class
class HandlerMixin(object):
action_handlers = {}
def add_handler_action(self,action):
if action not in self.action_handlers.keys():
self.action_handlers[action] = []
def register_handler(self, action, function):
self.add_handler_action(action)
if function not in self.action_handlers[action]:
self.action_handlers[action].append(function)
def call_handlers(self, action):
for each_func in self.action_handlers[action]:
each_func.__call__()
if __name__ == "__main__":
def test_function():
print "inside test function"
mything = HandlerMixin()
# This will only register the handler once per action even if you call it many times
mything.register_handler("on_wake", test_function)
mything.register_handler("on_wake", test_function)
mything.register_handler("on_wake", test_function)
mything.call_handlers("on_wake")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment