title: Registering per-class handlers
body: <p>I'm trying to find a good way to easily register handlers of some commands in a Python class. Those handlers would be registered for subclasses of <code>SomeBaseClass</code> and only available there. Unfortunately I'm starting to think I'm doing way more work than necessary. Right now, I've got:</p>
  
  <pre><code>def register_handlers(cls):
      cls._handlers = {}
      for method in cls.__dict__.values():
          if hasattr(method, "handler_name"):
              cls._handlers[method.handler_name] = method
      return cls
  
  class SomeBaseClass(object):
      _handlers = None
      def __init__(self):
          for h in self._handlers:
              self._handlers[h] = types.MethodType(self._handlers[h], self, SomeBaseClass)
      def run_action(self, name, *args):
          return self._handlers[name](*args)
  
  def actual_handler_wrapper(f):
      ....
      f.handler_name = name
      ....
  </code></pre>
  
  <p>There are a couple of issues here:</p>
  
  <ul>
  <li>both the class and it's handlers have to be decorated</li>
  <li>second level of subclasses is not easily available (<code>_handlers</code> would have to be assigned and checked on every level of inheritance)</li>
  <li>binding handlers to a class during initialisation seems dirty...</li>
  </ul>
  
  <p>Is there some way to improve this? I could probably get rid of <code>register_handlers</code> by changing <code>SomeBaseClass</code> to be a meta-class. It could also bind handlers at class creation time. But that seems even more complicated than the current approach.</p>
  
  <p>Is there some easier way out?</p>
  
  <p>Edit: Sample usage:</p>
  
  <pre><code>@register_handlers
  class SubClass(SomeBaseClass):
      @actual_handler_wrapper
      def handler(self):
         ...
  </code></pre>