kquick/Thespian

[Help wanted] Create actor with constructor (__init__ function)

Closed this issue · 4 comments

Hi,
Is it possible to create actors with init function? I don't see any examples in the documentation.
Thanks.

No. Your actor's __init__ cannot perform Actor-based activity because it is not fully an Actor yet. You can define and perform normal __init__ activities, but you may not call self.send() or other Actor methods in the __init__.

The recommended way to handle this is:

def MyActor(Actor):

    def __init__(self, *args, **kw):
        super(MyActor, self).__init__(*args, **kw)
        self._actor_startup_completed = False

    def perform_actor_startup(self):
        self.foo = self.createActor(OtherActor)
        self.send(self.foo, Message())

    def receiveMessage(self, message, sender):
        if not self._actor_startup_completed:
            perform_actor_startup()
        handle_message()

I'm closing this now, but please feel free to re-open if you have further questions.

Sorry to open an old issue, but this has come up while evaluating the framework. I'm looking to perform some initialization (i.e. start some child actors or initialize some resources). The recommendation above is alright (although a little ugly) but doesn't really work if I'm using ActorTypeDispatcher. I'll need to add that startup condition to every message handler. What I have been doing is starting the actor and immediately sending a message to initialize the function.

Maybe there could be a function that we could override after the actor has started? Or maybe a system message that always gets sent on actor startup?

The methodology in #64 (where you've also commented) addresses the ActorTypeDispatcher, so I'm planning to continue the discussion there unless you indicate otherwise here.