Created
April 4, 2016 19:45
-
-
Save pjz/740d7bf4fc5f21522c5e637ad848a73f to your computer and use it in GitHub Desktop.
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 characters
""" | |
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 characters
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() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment