Coding a simple state machine in python

Marko Rauhamaa marko at pacujo.net
Tue Feb 25 12:20:23 CET 2014


Peter Otten <__peter__ at web.de>:
> Why have the function return a name? Why not just another function?

As people have said, there are many ways to skin the cat.

A function can represent a state if it is the only type of event the
state machine must process. A regular expression parser would be an
example.

In the general case, a state machine is a matrix of M states by N types
of event. Then, one natural manner of representing a state is a nested
class:

    class Lackey:
        def __init__(self):
            lackey = self

            class Idle:
                def handle_ding(self):
                    lackey.start_timer(10)
                    lackey.set_state(Dinged)

            class Dinged:
                def handle_dong(self):
                    lackey.cancel_timer()
                    lackey.open_door()
                    lackey.ask_for_name()
                    lackey.start_timer(20)
                    lackey.set_state(AwaitingName)

                def handle_timeout(self):
                    lackey.open_door()
                    lackey.shoo_visitor_away()
                    lackey.set_state(Annoyed)

            # other state classes here...
            self.set_state(Idle)

        def set_state(self, state):
            log("Lackey(): New state: {}".format(
                    id(self), state.__class__.__name__))
            self.state = state()

        def handle_ding(self):
            self.state.handle_ding()

        def handle_dong(self):
            self.state.handle_dong()

        def handle_timeout(self):
            self.state.handle_timeout()

        def start_timer(self):
            # etc etc


Marko



More information about the Python-list mailing list