Skip to content

Instantly share code, notes, and snippets.

@pjz
Created March 11, 2016 15:38
Show Gist options
  • Save pjz/3f188092a1dd09f78702 to your computer and use it in GitHub Desktop.
Save pjz/3f188092a1dd09f78702 to your computer and use it in GitHub Desktop.
Another take on message handler registration
"""
RegistryActor - a dict-based dispatcher for actors
Usage:
from .actors import RegistryActor
class Hello(RegistryActor):
def __init__(self):
super(self.__class__, self).__init__()
self.registry[SomeMessageClass] = self.do_something
def do_something(self, message, sender):
pass
Pros:
* works with inheritance
Cons:
* uses inheritance (? is this a con?)
"""
from thespian.actors import Actor
class RegistryActor(Actor):
def __init__(self):
self.registry = {}
def receiveMessage(self, message, sender):
klass = message.__class__
if not klass in self.registry:
for k in self.registry:
if isinstance(message, k):
self.registry[klass] = self.registry[k]
break
method = self.registry.get(klass, getattr(self, 'receiveUnrecognizedMessage', None))
if method is not None:
method(self, message, sender)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment