I need help building a data structure for a state diagram
Paul McGuire
ptmcg at austin.rr.com
Mon May 25 12:04:10 EDT 2009
On May 24, 1:16 pm, Matthew Wilson <m... at tplus1.com> wrote:
> I'm working on a really simple workflow for my bug tracker. I want
> filed bugs to start in an UNSTARTED status. From there, they can go to
> STARTED.
>
I just wrote an article for the April issue of Python Magazine on how
to add embedded DSL code to your Python scripts using Python's imputil
module, and I used a state pattern for my example. Two state machine
examples I used to illustrate the work were a traffic light and a
library book checkin/checkout. The traffic light state machine is
just a simple cycle through the 3 light states. But the library book
state machine is more complex (your bug tracking example made me think
of it), with different transitions allowed one state into multiple
different states. Here is how the code looks for these examples:
==============
# trafficLight.pystate
statemachine TrafficLight:
Red -> Green
Green -> Yellow
Yellow -> Red
Red.carsCanGo = False
Yellow.carsCanGo = True
Green.carsCanGo = True
# ... other class definitions for state-specific behavior ...
==============
# trafficLightDemo.py
# add support for .pystate files, with
# embedded state machine DSL
import stateMachine
import trafficLight
tlight = trafficLight.Red()
while 1:
print tlight, "GO" if tlight.carsCanGo else "STOP"
tlight.delay()
tlight = tlight.next_state()
==============
# libraryBook.pystate
statemachine BookCheckout:
New -(create)-> Available
Available -(reserve)-> Reserved
Available -(checkout)-> CheckedOut
Reserved -(cancel)-> Available
Reserved -(checkout)-> CheckedOut
CheckedOut -(checkin)-> Available
CheckedOut -(renew)-> CheckedOut
You don't need to adopt this whole DSL implementation, but the article
might give you some other ideas.
-- Paul
More information about the Python-list
mailing list