Created
April 4, 2016 19:45
Revisions
-
pjz created this gist
Apr 4, 2016 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,57 @@ """ Using a class decorator Usage: @Actorize class Hello(Actor): @handle(SomeMessageClass) def somemethod(self, msg, sender): pass """ import inspect def Actorize(cls): def receiveMessage(self, message, sender): klass = message.__class__ registry = self._msg_registry if not klass in registry: for k in registry: if isinstance(message, k): registry[klass] = registry[k] break method = registry.get(klass, None) if method is not None: method(self, message, sender) # make sure cls is a subclass of Actor #if not Actor in cls.__bases__: # cls.__class__ = type(cls.__name__, (cls, Actor), { 'receiveMessage': receiveMessage }) # inheritance makes this possible (subclass of a decorated class) if not hasattr(cls, '_msg_registry'): cls._msg_registry = {} # gather up all the handle-marked methods into the registry for name, method in inspect.getmembers(cls, predicate=inspect.ismethod): if hasattr(method, 'handles'): for klass in method.handles: cls._msg_registry[klass] = method cls.receiveMessage = receiveMessage return cls def handle(klass): def wrapper(f): f.handles = getattr(f, 'handles', []) + [ klass ] return f return wrapper This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,25 @@ from thespian.actors import ActorSystem, Actor from actorize import Actorize, handle @Actorize class Hello(Actor): @handle(type('')) def hello(self, message, sender): self.send(sender, 'Hello, string!') @handle(type(1)) def hi(self, msg, sender): self.send(sender, 'Hello, int!') def say_hello(): hello = ActorSystem().createActor(Hello) print(ActorSystem().ask(hello, 'are you there?', 1.5)) print(ActorSystem().ask(hello, 1, 1.5)) if __name__ == "__main__": say_hello()