Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Code Reviews

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

A state machine in Python

+4
−0

I've written the following code implementing a state machine in Python, and I'd like some feedback on it.

The basic idea is that each state has a set of corresponding actions that trigger a state change. You can register observer functions with states, which are then called whenever the state is entered.

"""
State machine
"""

from typing import Callable, Iterable, Mapping, List, Optional


ObserverFunction = Callable[[str, Optional["State"], "State"], None]


class State:
    """
    Describes a single state
    """
    def __init__(self, name: str, action_map: Mapping[str, str],
                 observers: Optional[Iterable[ObserverFunction]] = None):
        self._name = name
        self._observers: List[ObserverFunction] = list(observers or [])
        self._action_map = action_map


    def __str__(self):
        return self._name


    def register(self, observer: ObserverFunction) -> None:
        """
        Register an observer.
        """
        self._observers.append(observer)


    def enter(self, action: str, prev_state: Optional["State"] = None) -> None:
        """
        Notify all observers that this now is the current state
        """
        for observer in self._observers:
            observer(action, prev_state, self)


    def next_state(self, state_machine: "StateMachine", action: str) -> "State":
        """
        return the new state caused by the action
        """
        if not action in self._action_map:
            raise ValueError(f"State {self} does not support action {action}")
        new_state = state_machine.get_state(self._action_map[action])

        return new_state


    def get_actions(self) -> Iterable[str]:
        """
        return the possible actions on the state
        """
        return self._action_map.keys()


    def is_final(self):
        """
        Return if this state is final, that is, no actions are defined.
        """
        return not self._action_map



class StateMachine:
    """
    Describes a state machine
    """
    def __init__(self, description: Iterable[State], first: str):
        state_names = []
        for state in description:
            name = str(state)
            if name in state_names:
                raise ValueError(f"Duplicate state name: {name}")
            state_names.append(name)

        if not first in state_names:
            raise ValueError(f"No state {first} in {description}")

        self._states = { str(state): state for state in description }
        self._current_state = self._states[first]
        self._current_state.enter("initial state")


    def perform(self, action: str) -> None:
        """
        Perform an action on the current state machine.

        An action potentially changes the state, notifying its observers.
        """
        prev_state = self._current_state
        self._current_state = prev_state.next_state(self, action)
        self._current_state.enter(action, prev_state)


    def get_state(self, name: str) -> State:
        """
        Get state by name
        """
        try:
            return self._states[name]
        except KeyError as error:
            raise ValueError(f"State machine does not contain state {name}") from error


    def get_current_state(self) -> State:
        """
        Get the current state
        """
        return self._current_state


    def has_terminated(self):
        """
        Return True if the state machin has reached a final state
        """
        return self._current_state.is_final()


    def get_all_actions(self):
        """
        Get the set of all actions of all states in the state machine
        """
        all_actions = set()
        for state in self._states.values():
            all_actions.update(state.get_actions())
        return all_actions

The following code demonstrates the intended use:

from statemachine import State, StateMachine


def report(action, old_state, new_state):
    if action == "initial state":
        action = "exist"

    print(f"I was {old_state or 'nothing'}, but you wanted me to {action}, so now I'm {new_state}.") 


def tell_emotion(action, old_state, new_state):
    feelings = {
        'waiting': 'boring',
        'running': 'exhausting',
        'sleeping': 'refreshing' }
    feeling = feelings[str(new_state)]
    print(f"To be {new_state} is {feeling}.")


def final_message(*args):
    print("You monster!")


def main():
    sm = StateMachine([State('waiting',
                             { 'sleep': 'sleeping', 
                               'run': 'running', 
                               'die': 'dead' },
                             [report, tell_emotion]), 
                       State('sleeping',
                             { 'wake up': 'waiting', 
                               'die': 'dead' },
                             [report, tell_emotion]), 
                       State('running',
                             { 'stop': 'waiting', 
                               'die': 'dead' },
                             [report, tell_emotion]), 
                       State('dead', {}, [report, final_message])], 
                      "waiting")
    all_actions = sm.get_all_actions()

    try:
        while not sm.has_terminated(): 
            state = sm.get_current_state()
            print("Available actions:", ", ".join(state.get_actions()))
            try:
                action = input("what should I do? ")
                sm.perform(action)
            except ValueError:
                if action in all_actions:
                    print(f"I can't {action} when I'm {state}!")
                else:
                    print(f"I don't know how to {action}!")
    except EOFError:
        print("Hey, you disappeared!")


if __name__ == '__main__':
    main()
History
Why does this post require moderator attention?
You might want to add some details to your flag.
Why should this post be closed?

2 comment threads

other state machine examples (1 comment)
Context/Goal? (2 comments)

2 answers

You are accessing this answer with a direct link, so it's being shown above all other answers regardless of its score. You can return to the normal view.

+4
−0

Some thoughts about your design / code (not repeating what was already said by Derek):

  • You have chosen member _observers of class State to be a list, and member function register to append to that list. Consequently, the same observer can be registered more than once, and the order of execution is defined. This may certainly be intended - if not, you might consider to ignore attempts to register an observer a second time or even use a set to store the observers. In any case, I recommend describing the desired semantics of register more explicitly.

  • Somehow the existence of the register method feels a bit asymmetric anyway, since this is the only interface to make adjustments to the state machine at runtime. Everything else is statically defined at construction time, including the initial set of observers. Maybe register is not even necessary at all?

  • In your code, state transitions are triggered by what you call "actions". This nomenclature may be fine for your usage of the state machine, but it appeared a bit unusual to me: I would have expected state transitions to be triggered by "events". The _action_map could from my point of view also just be called "transitions".

  • The name of the method enter seems a bit unfortunate: The name does not describe very well what the method does. From looking at the comment for the function, a name like notify_observers would appear more natural.

  • The string "initial state" does not fit well for neither an action nor an event. Maybe just "init" or a special object (to avoid any conflict with user defined actions)? It would also make sense to provide this via an API rather than have this string literal directly in the client code.

  • There are already some error checks. There is nothing to detect unreachable states, though.

Apart from the above remarks, I find the approach well suited to define certain types of small state machines. It is in fact fairly flexible due to the fact that you call observers with the action, the previous state and the new state: This allows a user to realize state-oriented reactions (Moore-machine) as well as transition-oriented reactions (Mealy-machine).

Your example is nicely chosen to demonstrate the configuration and use of the state machine: The configuration of the example state machine and the client code are really easy to understand.

History
Why does this post require moderator attention?
You might want to add some details to your flag.

1 comment thread

Thank you for your feedback. You've got a few good points. I didn't actually think of double-register... (1 comment)
+4
−0

I think you've got an architectural error. A state machine (SM) determines it's own actions based on it's state and the messages it may receive. The calling code may send messages (information) to a SM. But the calling code shouldn't send actions (imperative commands) to a SM.

A SM should be able to ignore a message which it doesn't know how to react to. Maybe in some states the SM reacts to the message, in other states it doesn't react, and the SM happens to be in a state in which it doesn't react. Maybe the SM never reacts to that message in a any state. In these cases, the SM should ignore the message if doesn't know how to react to it. The SM shouldn't raise an exception, because this situation is normal. The calling code which sends the message shouldn't know the state of the SM. It should pump messages to the SM, and let the SM take care of itself.

def next_state(self, state_machine: "StateMachine", action: str) -> "State":
    """
    return the new state caused by the action
    """
    if not action in self._action_map:
        raise ValueError(f"State {self} does not support action {action}")
    new_state = state_machine.get_state(self._action_map[action])

    return new_state
History
Why does this post require moderator attention?
You might want to add some details to your flag.

2 comment threads

On actions vs. events (actions are *not* commands!) (1 comment)
Not all information / events makes sense in all states (1 comment)

Sign up to answer this question »