Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #67010 > unrolled thread

Coding a simple state machine in python

Started byRonaldo <abhishek1899@gmail.com>
First post2014-02-24 17:30 -0800
Last post2014-02-24 20:54 -0500
Articles 12 — 8 participants

Back to article view | Back to comp.lang.python


Contents

  Coding a simple state machine in python Ronaldo <abhishek1899@gmail.com> - 2014-02-24 17:30 -0800
    Re: Coding a simple state machine in python Tim Daneliuk <tundra@tundraware.com> - 2014-02-24 19:46 -0600
    Re: Coding a simple state machine in python William Ray Wing <wrw@mac.com> - 2014-02-24 21:55 -0500
      Re: Coding a simple state machine in python Tim Daneliuk <tundra@tundraware.com> - 2014-02-24 21:27 -0600
      Re: Coding a simple state machine in python Tim Daneliuk <tundra@tundraware.com> - 2014-02-24 21:27 -0600
        Re: Coding a simple state machine in python alex23 <wuwei23@gmail.com> - 2014-02-25 15:19 +1000
          Re: Coding a simple state machine in python Mark Lawrence <breamoreboy@yahoo.co.uk> - 2014-02-25 08:35 +0000
          Re: Coding a simple state machine in python Peter Otten <__peter__@web.de> - 2014-02-25 11:01 +0100
            Re: Coding a simple state machine in python alex23 <wuwei23@gmail.com> - 2014-03-03 14:49 +1000
    Re: Coding a simple state machine in python Peter Otten <__peter__@web.de> - 2014-02-25 11:04 +0100
      Re: Coding a simple state machine in python Marko Rauhamaa <marko@pacujo.net> - 2014-02-25 13:20 +0200
    Re: Coding a simple state machine in python Roy Smith <roy@panix.com> - 2014-02-24 20:54 -0500

#67010 — Coding a simple state machine in python

FromRonaldo <abhishek1899@gmail.com>
Date2014-02-24 17:30 -0800
SubjectCoding a simple state machine in python
Message-ID<65ac9612-fd48-472a-b077-c802be96ece3@googlegroups.com>
How do I write a state machine in python? I have identified the states and the conditions. Is it possible to do simple a if-then-else sort of an algorithm? Below is some pseudo code:

if state == "ABC":
   do_something()
   change state to DEF

if state == "DEF"
   perform_the_next_function()
...

I have a class to which certain values are passed from a GUI and the functions above have to make use of those variables. How do I go about doing this? I have the following algorithm:

class TestClass():
    def __init__(self, var1, var2): #var1 and var2 are received from a GUI
       self.var1 = var1
...
    if state == "ABC"
       doSomething(var1, var2)
..

Could someone point me in the right direction? Thank you!
   

[toc] | [next] | [standalone]


#67011

FromTim Daneliuk <tundra@tundraware.com>
Date2014-02-24 19:46 -0600
Message-ID<589tta-krl.ln1@ozzie.tundraware.com>
In reply to#67010
On 02/24/2014 07:30 PM, Ronaldo wrote:
> How do I write a state machine in python? I have identified the states and the conditions. Is it possible to do simple a if-then-else sort of an algorithm? Below is some pseudo code:
>
> if state == "ABC":
>     do_something()
>     change state to DEF
>
> if state == "DEF"
>     perform_the_next_function()
> ...
>
> I have a class to which certain values are passed from a GUI and the functions above have to make use of those variables. How do I go about doing this? I have the following algorithm:
>
> class TestClass():
>      def __init__(self, var1, var2): #var1 and var2 are received from a GUI
>         self.var1 = var1
> ...
>      if state == "ABC"
>         doSomething(var1, var2)
> ..
>
> Could someone point me in the right direction? Thank you!
>
>

There are probably lots of ways to do it, but I'd use a dictionary and
a variable to hold the current state:

CURRENT_STATE = "Start"
DFA_STATE_MACHINE = {"Start" : start_fn, "State1" : state1_fn, "State2" : state2_fn ....}

#####
# Functions for each state go here.  They end by setting CURRENT_STATE to some value
#####

def start_fn():
.
.
.


def state1_fn():

.
.
.


# And so on


# Now run the state machine

while ( CURRENT_STATE != "Done"):

     # Execute the function for the current state

     DFA_STATE_MACHINE[CURRENT_STATE]()


Like I said, there are other - more compact ways - to do this, but this
is the general idea.   Now - go do your own homework :)



-- 
----------------------------------------------------------------------------
Tim Daneliuk     tundra@tundraware.com
PGP Key:         http://www.tundraware.com/PGP/

[toc] | [prev] | [next] | [standalone]


#67016

FromWilliam Ray Wing <wrw@mac.com>
Date2014-02-24 21:55 -0500
Message-ID<mailman.7338.1393296954.18130.python-list@python.org>
In reply to#67010
On Feb 24, 2014, at 8:30 PM, Ronaldo <abhishek1899@gmail.com> wrote:

> How do I write a state machine in python? I have identified the states and the conditions. Is it possible to do simple a if-then-else sort of an algorithm? Below is some pseudo code:
> 
> if state == "ABC":
>   do_something()
>   change state to DEF
> 
> if state == "DEF"
>   perform_the_next_function()
> ...
> 
> I have a class to which certain values are passed from a GUI and the functions above have to make use of those variables. How do I go about doing this? I have the following algorithm:
> 
> class TestClass():
>    def __init__(self, var1, var2): #var1 and var2 are received from a GUI
>       self.var1 = var1
> ...
>    if state == "ABC"
>       doSomething(var1, var2)
> ..
> 
> Could someone point me in the right direction? Thank you!
> 
> -- 
> https://mail.python.org/mailman/listinfo/python-list

And, to extend Tim's suggestion of a dictionary just a bit, note that since Python functions are happy to pass function names as arguments, you can use a dictionary to make a really nice compact dispatch table.  That is, function A does its thing, gets to a new state, and returns as one of its return arguments the key into the dictionary that points to the next function_name to be called based on that new state.

Stackoverflow has a couple of compact examples here:  

http://stackoverflow.com/questions/715457/how-do-you-implement-a-dispatch-table-in-your-language-of-choice

Bill

[toc] | [prev] | [next] | [standalone]


#67017

FromTim Daneliuk <tundra@tundraware.com>
Date2014-02-24 21:27 -0600
Message-ID<530C0DA2.7020202@tundraware.com>
In reply to#67016
On 02/24/2014 08:55 PM, William Ray Wing wrote:
>
> On Feb 24, 2014, at 8:30 PM, Ronaldo <abhishek1899@gmail.com> wrote:
>
>> How do I write a state machine in python? I have identified the states and the conditions. Is it possible to do simple a if-then-else sort of an algorithm? Below is some pseudo code:
>>
>> if state == "ABC":
>>    do_something()
>>    change state to DEF
>>
>> if state == "DEF"
>>    perform_the_next_function()
>> ...
>>
>> I have a class to which certain values are passed from a GUI and the functions above have to make use of those variables. How do I go about doing this? I have the following algorithm:
>>
>> class TestClass():
>>     def __init__(self, var1, var2): #var1 and var2 are received from a GUI
>>        self.var1 = var1
>> ...
>>     if state == "ABC"
>>        doSomething(var1, var2)
>> ..
>>
>> Could someone point me in the right direction? Thank you!
>>
>> --
>> https://mail.python.org/mailman/listinfo/python-list
>
> And, to extend Tim's suggestion of a dictionary just a bit, note that since Python functions are happy to pass function names as arguments, you can use a dictionary to make a really nice compact dispatch table.  That is, function A does its thing, gets to a new state, and returns as one of its return arguments the key into the dictionary that points to the next function_name to be called based on that new state.
>
> Stackoverflow has a couple of compact examples here:
>
> http://stackoverflow.com/questions/715457/how-do-you-implement-a-dispatch-table-in-your-language-of-choice
>
> Bill
>


Now you're making it TOO easy Bill ;)

-- 
----------------------------------------------------------------------------
Tim Daneliuk     tundra@tundraware.com
PGP Key:         http://www.tundraware.com/PGP/

[toc] | [prev] | [next] | [standalone]


#67018

FromTim Daneliuk <tundra@tundraware.com>
Date2014-02-24 21:27 -0600
Message-ID<mailman.7339.1393299066.18130.python-list@python.org>
In reply to#67016
On 02/24/2014 08:55 PM, William Ray Wing wrote:
>
> On Feb 24, 2014, at 8:30 PM, Ronaldo <abhishek1899@gmail.com> wrote:
>
>> How do I write a state machine in python? I have identified the states and the conditions. Is it possible to do simple a if-then-else sort of an algorithm? Below is some pseudo code:
>>
>> if state == "ABC":
>>    do_something()
>>    change state to DEF
>>
>> if state == "DEF"
>>    perform_the_next_function()
>> ...
>>
>> I have a class to which certain values are passed from a GUI and the functions above have to make use of those variables. How do I go about doing this? I have the following algorithm:
>>
>> class TestClass():
>>     def __init__(self, var1, var2): #var1 and var2 are received from a GUI
>>        self.var1 = var1
>> ...
>>     if state == "ABC"
>>        doSomething(var1, var2)
>> ..
>>
>> Could someone point me in the right direction? Thank you!
>>
>> --
>> https://mail.python.org/mailman/listinfo/python-list
>
> And, to extend Tim's suggestion of a dictionary just a bit, note that since Python functions are happy to pass function names as arguments, you can use a dictionary to make a really nice compact dispatch table.  That is, function A does its thing, gets to a new state, and returns as one of its return arguments the key into the dictionary that points to the next function_name to be called based on that new state.
>
> Stackoverflow has a couple of compact examples here:
>
> http://stackoverflow.com/questions/715457/how-do-you-implement-a-dispatch-table-in-your-language-of-choice
>
> Bill
>


Now you're making it TOO easy Bill ;)

-- 
----------------------------------------------------------------------------
Tim Daneliuk     tundra@tundraware.com
PGP Key:         http://www.tundraware.com/PGP/

[toc] | [prev] | [next] | [standalone]


#67023

Fromalex23 <wuwei23@gmail.com>
Date2014-02-25 15:19 +1000
Message-ID<leh95u$4aa$1@dont-email.me>
In reply to#67018
On 25/02/2014 1:27 PM, Tim Daneliuk wrote:
> On 02/24/2014 08:55 PM, William Ray Wing wrote:
>> On Feb 24, 2014, at 8:30 PM, Ronaldo <abhishek1899@gmail.com> wrote:
>>> How do I write a state machine in python?
 >>
>> Stackoverflow has a couple of compact examples here:
>
> Now you're making it TOO easy Bill ;)

No, the _easy_ solution is:

https://pypi.python.org/pypi?%3Aaction=search&term=state++machine&submit=search

[toc] | [prev] | [next] | [standalone]


#67034

FromMark Lawrence <breamoreboy@yahoo.co.uk>
Date2014-02-25 08:35 +0000
Message-ID<mailman.7347.1393317566.18130.python-list@python.org>
In reply to#67023
On 25/02/2014 05:19, alex23 wrote:
> On 25/02/2014 1:27 PM, Tim Daneliuk wrote:
>> On 02/24/2014 08:55 PM, William Ray Wing wrote:
>>> On Feb 24, 2014, at 8:30 PM, Ronaldo <abhishek1899@gmail.com> wrote:
>>>> How do I write a state machine in python?
>  >>
>>> Stackoverflow has a couple of compact examples here:
>>
>> Now you're making it TOO easy Bill ;)
>
> No, the _easy_ solution is:
>
> https://pypi.python.org/pypi?%3Aaction=search&term=state++machine&submit=search
>

Or several recipes on Activestate.

-- 
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.

Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection is active.
http://www.avast.com

[toc] | [prev] | [next] | [standalone]


#67036

FromPeter Otten <__peter__@web.de>
Date2014-02-25 11:01 +0100
Message-ID<mailman.7350.1393322496.18130.python-list@python.org>
In reply to#67023
alex23 wrote:

> On 25/02/2014 1:27 PM, Tim Daneliuk wrote:
>> On 02/24/2014 08:55 PM, William Ray Wing wrote:
>>> On Feb 24, 2014, at 8:30 PM, Ronaldo <abhishek1899@gmail.com> wrote:
>>>> How do I write a state machine in python?
>  >>
>>> Stackoverflow has a couple of compact examples here:
>>
>> Now you're making it TOO easy Bill ;)
> 
> No, the _easy_ solution is:
> 
> 
https://pypi.python.org/pypi?%3Aaction=search&term=state++machine&submit=search

Easy? By the time I have evaluated these I've written my own ;)

[toc] | [prev] | [next] | [standalone]


#67509

Fromalex23 <wuwei23@gmail.com>
Date2014-03-03 14:49 +1000
Message-ID<lf11lk$k67$1@dont-email.me>
In reply to#67036
On 25/02/2014 8:01 PM, Peter Otten wrote:
> alex23 wrote:
>> No, the _easy_ solution is [find a suitable package on PyPI]
>
> Easy? By the time I have evaluated these I've written my own ;)

It's never writing a solution that's the problem...it's maintaining it 
over time :)

[toc] | [prev] | [next] | [standalone]


#67037

FromPeter Otten <__peter__@web.de>
Date2014-02-25 11:04 +0100
Message-ID<mailman.7351.1393322706.18130.python-list@python.org>
In reply to#67010
William Ray Wing wrote:

> 
> On Feb 24, 2014, at 8:30 PM, Ronaldo <abhishek1899@gmail.com> wrote:
> 
>> How do I write a state machine in python? I have identified the states
>> and the conditions. Is it possible to do simple a if-then-else sort of an
>> algorithm? Below is some pseudo code:
>> 
>> if state == "ABC":
>>   do_something()
>>   change state to DEF
>> 
>> if state == "DEF"
>>   perform_the_next_function()
>> ...
>> 
>> I have a class to which certain values are passed from a GUI and the
>> functions above have to make use of those variables. How do I go about
>> doing this? I have the following algorithm:
>> 
>> class TestClass():
>>    def __init__(self, var1, var2): #var1 and var2 are received from a GUI
>>       self.var1 = var1
>> ...
>>    if state == "ABC"
>>       doSomething(var1, var2)
>> ..
>> 
>> Could someone point me in the right direction? Thank you!
>> 
>> --
>> https://mail.python.org/mailman/listinfo/python-list
> 
> And, to extend Tim's suggestion of a dictionary just a bit, note that
> since Python functions are happy to pass function names as arguments, you
> can use a dictionary to make a really nice compact dispatch table.  That
> is, function A does its thing, gets to a new state, and returns as one of
> its return arguments the key into the dictionary that points to the next
> function_name to be called based on that new state.
> 
> Stackoverflow has a couple of compact examples here:
> 
> http://stackoverflow.com/questions/715457/how-do-you-implement-a-dispatch-
table-in-your-language-of-choice

Why have the function return a name? Why not just another function?

[toc] | [prev] | [next] | [standalone]


#67038

FromMarko Rauhamaa <marko@pacujo.net>
Date2014-02-25 13:20 +0200
Message-ID<87lhwz1ls8.fsf@elektro.pacujo.net>
In reply to#67037
Peter Otten <__peter__@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

[toc] | [prev] | [next] | [standalone]


#67358

FromRoy Smith <roy@panix.com>
Date2014-02-24 20:54 -0500
Message-ID<roy-F51848.20540624022014@news.panix.com>
In reply to#67010
In article <65ac9612-fd48-472a-b077-c802be96ece3@googlegroups.com>,
 Ronaldo <abhishek1899@gmail.com> wrote:

> How do I write a state machine in python? I have identified the states and 
> the conditions. Is it possible to do simple a if-then-else sort of an 
> algorithm? Below is some pseudo code:
> 
> if state == "ABC":
>    do_something()
>    change state to DEF
> 
> if state == "DEF"
>    perform_the_next_function()

There's lots of ways to code state machines in Python.  The last time I 
did one, I made each state a function.  Each function returned a 
(next_state, output) tuple.  I don't know if that's the best way, but it 
worked and seemed logical to me.  Here's a trivial example with just two 
states:

class StateMachine:
    def __init__(self):
        self.state = self.start

    def process(self, input):
        for item in input:
            self.state, output = self.state(item)
            print output

    def start(self, item):
        if item > 5:
            return self.end, "done"
        else:
            return self.start, "still looking"

    def end(self, item):
        if item < 3:
            return self.start, "back to the beginning"
        else:
            return self.end, "still stuck at the end"

sm = StateMachine()
sm.process([1, 2, 6, 4, 2, 2])


When you run it, it should print:

still looking
still looking
done
still stuck at the end
back to the beginning
still looking

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web