Actors

class pykka.Actor(*_args: Any, **_kwargs: Any)[source]

An actor is an execution unit that executes concurrently with other actors.

To create an actor:

  1. subclass one of the Actor implementations:

  2. implement your methods, including __init__(), as usual,

  3. call Actor.start() on your actor class, passing the method any arguments for your constructor.

To stop an actor, call Actor.stop() or ActorRef.stop().

For example:

import pykka

class MyActor(pykka.ThreadingActor):
    def __init__(self, my_arg=None):
        super().__init__()
        ... # My optional init code with access to start() arguments

    def on_start(self):
        ... # My optional setup code in same context as on_receive()

    def on_stop(self):
        ... # My optional cleanup code in same context as on_receive()

    def on_failure(self, exception_type, exception_value, traceback):
        ... # My optional cleanup code in same context as on_receive()

    def on_receive(self, message):
        ... # My optional message handling code for a plain actor

    def a_method(self, ...):
        ... # My regular method to be used through an ActorProxy

my_actor_ref = MyActor.start(my_arg=...)
my_actor_ref.stop()
classmethod start(*args: Any, **kwargs: Any) ActorRef[A][source]

Start an actor.

Starting an actor also registers it in the ActorRegistry.

Any arguments passed to start() will be passed on to the class constructor.

Behind the scenes, the following is happening when you call start():

  1. The actor is created:

    1. actor_urn is initialized with the assigned URN.

    2. actor_inbox is initialized with a new actor inbox.

    3. actor_ref is initialized with a pykka.ActorRef object for safely communicating with the actor.

    4. At this point, your __init__() code can run.

  2. The actor is registered in pykka.ActorRegistry.

  3. The actor receive loop is started by the actor’s associated thread/greenlet.

Returns:

a ActorRef which can be used to access the actor in a safe manner

property actor_ref: ActorRef[A]

The actor’s ActorRef instance.

actor_urn: str

The actor URN string is a universally unique identifier for the actor. It may be used for looking up a specific actor using ActorRegistry.get_by_urn().

actor_inbox: ActorInbox

The actor’s inbox. Use ActorRef.tell(), ActorRef.ask(), and friends to put messages in the inbox.

actor_stopped: Event

A threading.Event representing whether or not the actor should continue processing messages. Use stop() to change it.

stop() None[source]

Stop the actor.

It’s equivalent to calling ActorRef.stop() with block=False.

on_start() None[source]

Run code at the beginning of the actor’s life.

Hook for doing any setup that should be done after the actor is started, but before it starts processing messages.

For ThreadingActor, this method is executed in the actor’s own thread, while __init__() is executed in the thread that created the actor.

If an exception is raised by this method the stack trace will be logged, and the actor will stop.

on_stop() None[source]

Run code at the end of the actor’s life.

Hook for doing any cleanup that should be done after the actor has processed the last message, and before the actor stops.

This hook is not called when the actor stops because of an unhandled exception. In that case, the on_failure() hook is called instead.

For ThreadingActor this method is executed in the actor’s own thread, immediately before the thread exits.

If an exception is raised by this method the stack trace will be logged, and the actor will stop.

on_failure(exception_type: type[BaseException] | None, exception_value: BaseException | None, traceback: TracebackType | None) None[source]

Run code when an unhandled exception is raised.

Hook for doing any cleanup after an unhandled exception is raised, and before the actor stops.

For ThreadingActor this method is executed in the actor’s own thread, immediately before the thread exits.

The method’s arguments are the relevant information from sys.exc_info().

If an exception is raised by this method the stack trace will be logged, and the actor will stop.

on_receive(message: Any) Any[source]

May be implemented for the actor to handle regular non-proxy messages.

Parameters:

message (any) – the message to handle

Returns:

anything that should be sent as a reply to the sender

class pykka.ActorRef(actor: A)[source]

Reference to a running actor which may safely be passed around.

ActorRef instances are returned by Actor.start() and the lookup methods in ActorRegistry. You should never need to create ActorRef instances yourself.

Parameters:

actor (Actor) – the actor to wrap

actor_class: type[A]

The class of the referenced actor.

actor_urn: str

See Actor.actor_urn.

actor_inbox: ActorInbox

See Actor.actor_inbox.

actor_stopped: Event

See Actor.actor_stopped.

is_alive() bool[source]

Check if actor is alive.

This is based on the actor’s stopped flag. The actor is not guaranteed to be alive and responding even though is_alive() returns True.

Returns:

Returns True if actor is alive, False otherwise.

tell(message: Any) None[source]

Send message to actor without waiting for any response.

Will generally not block, but if the underlying queue is full it will block until a free slot is available.

Parameters:

message (any) – message to send

Raise:

pykka.ActorDeadError if actor is not available

Returns:

nothing

ask(message: Any, *, block: Literal[False], timeout: float | None = None) Future[Any][source]
ask(message: Any, *, block: Literal[True], timeout: float | None = None) Any
ask(message: Any, *, block: bool = True, timeout: float | None = None) Any | Future[Any]

Send message to actor and wait for the reply.

The message can be of any type. If block is False, it will immediately return a Future instead of blocking.

If block is True, and timeout is None, as default, the method will block until it gets a reply, potentially forever. If timeout is an integer or float, the method will wait for a reply for timeout seconds, and then raise pykka.Timeout.

Parameters:
  • message (any) – message to send

  • block (boolean) – whether to block while waiting for a reply

  • timeout (float or None) – seconds to wait before timeout if blocking

Raise:

pykka.Timeout if timeout is reached if blocking

Raise:

any exception returned by the receiving actor if blocking

Returns:

pykka.Future, or response if blocking

stop(*, block: Literal[True], timeout: float | None = None) bool[source]
stop(*, block: Literal[False], timeout: float | None = None) Future[bool]
stop(*, block: bool = True, timeout: float | None = None) Any | Future[Any]

Send a message to the actor, asking it to stop.

Returns True if actor is stopped or was being stopped at the time of the call. False if actor was already dead. If block is False, it returns a future wrapping the result.

Messages sent to the actor before the actor is asked to stop will be processed normally before it stops.

Messages sent to the actor after the actor is asked to stop will be replied to with pykka.ActorDeadError after it stops.

The actor may not be restarted.

block and timeout works as for ask().

Returns:

pykka.Future, or a boolean result if blocking

proxy() ActorProxy[A][source]

Wrap the ActorRef in an ActorProxy.

Using this method like this:

proxy = AnActor.start().proxy()

is analogous to:

proxy = ActorProxy(AnActor.start())
Raise:

pykka.ActorDeadError if actor is not available

Returns:

pykka.ActorProxy