state machine for humans
There are two types of developers in this world: those who love state machines and those who will eventually.
I fall in the first camp. I think it is really important to have a
declarative way to define the states of an object. That’s why I
developed pysm
.
pip install pysm
An InvalidStateTransition Exception will be thrown if you try to move into an invalid state.
We have basic support for mongoengine, and sqlalchemy.
Just have your object inherit from mongoengine.Document
and
state_machine will add a StringField for state.
Note: You must explicitly call #save to persist the document to the datastore.
@pysm.state_machine
class Person(mongoengine.Document):
name = mongoengine.StringField(default='Billy')
class Sleeping(pysm.State):
initial = True
def enter_state(self, from_state):
pass
def exit_state(self, to_state):
pass
class Running(pysm.State):
def enter_state(self, from_state):
pass
def exit_state(self, to_state):
pass
class Cleaning(pysm.State):
def enter_state(self, from_state):
pass
def exit_state(self, to_state):
pass
run = Event(from_states=Sleeping, to_state=Running)
cleanup = Event(from_states=Running, to_state=Cleaning)
sleep = Event(from_states=(Running, Cleaning), to_state=Sleeping)
person = Person()
person.save()
eq_(person.current_state, Person.Sleeping)
assert person.is_sleeping
assert not person.is_running
person.run()
assert person.is_running
person.sleep()
assert person.is_sleeping
person.run()
person.save()
All you need to do is have sqlalchemy manage your object. For example:
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
@pysm.state_machine
class Puppy(Base):
...
to aasm and ruby’s state_machine and jtushman's jtushman/state_machine and all other state machines that I loved before