Hacker News new | ask | show | jobs
by siddhant 3280 days ago
In case you're using Python, I can't recommend this library enough - https://github.com/pytransitions/transitions . An absolute pleasure to work with.
2 comments

For goodness' sake, no! I just ripped that package out of our production code. It's terrible! It adds methods to your object at runtime, crazy stuff.

I replaced it with just this:

        class StateMachine(object):
	    '''
	    A very simple FSM class.

	    Params:
	        initial: Initial state
	        table: A dict (current, event) -> target
	    '''

	    def __init__(self, initial, table):
	        self.current_state = initial
	        self.state_table = table

	    def __call__(self, event):
	        '''Trigger one state transition.'''
	        self.current_state = self.state_table[self.current_state, event]


	class Foo(object):

	    STATE_TABLE = {
		(current_state, event): next_state,
		...
	    }

	    def __init__(self, xid, token, config):
		self.fsm = StateMachine('start', self.STATE_TABLE)

	    def begin(self):
	        while self.fsm.current_state not in {'success', 'error'}:
	            method = getattr(self, self.fsm.current_state)
	            self.fsm(method())
	        if self.fsm.current_state == 'error':
	            self.report_error()


If you're using Python anything more involved than a dict mapping (current, transition) -> next is just overkill. Use it, don't abuse it. ;-)
SMC (State Machine Compiler - http://smc.sourceforge.net/) supports multiple languages and is fairly simple to learn and use.