Help with coroutine-based state machines?
Yair Chuchem
yairchu at 012.net.il
Fri May 30 04:54:07 EDT 2003
How about this implemetation of your state-machine, without the cluttering
of the while loops, and as a side effect, without use of generators too:
### Code snippet start
class FSM:
def __init__(self, startnum, incrnum, stopnum):
self.startnum = startnum
self.incrnum = incrnum
self.stopnum = stopnum
self.counter = 0
self.exit = 'exitsentinel'
def idle(self):
# We could wait for some condition here.
print "Idle state: %d" % self.counter
return self.start
def start(self):
self.counter = self.startnum
print "Start state: %d" % self.counter
return self.increment
def increment(self):
self.counter = self.counter + self.incrnum
print "Increment state: %d" % self.counter
return self.checkfinished
def checkfinished(self):
if self.counter >= self.stopnum:
return self.finished
else:
return self.increment
def finished(self):
print "Finished state: %d" % self.counter
return self.exit
def dispatch(self, startstate):
newstate = startstate
while newstate<>self.exit:
newstate = newstate()
if __name__ == "__main__":
m = FSM(1,5,50)
m.dispatch(m.idle)
m.dispatch(m.idle)
### Code snippet end
Is there something I'm missing?
Yair
More information about the Python-list
mailing list