Skip to content

Finite State Machine for Python (based on Jake Gordon's javascript-state-machine)

Notifications You must be signed in to change notification settings

TaylorIsAGoodboy/fysom

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Travis build status image Coverage status Latest PyPI version

License

MIT licensed. All credits go to Jake Gordon for the original javascript implementation and to Mansour Behabadi for the python port.

Synopsis

This is basically Mansours' implementation with unit tests and a build process added. It's also on PyPi (pip install fysom). Fysom is built and tested on python 2.6 to 3.5 and PyPy.

Installation

From your friendly neighbourhood cheeseshop

pip install fysom

Developer setup

This module uses PyBuilder.

pip install pybuilder

Running the tests

pyb verify

Generating and using a setup.py

pyb package -E linux-release
cd target/dist/fysom-$VERSION
./setup.py bdist_rpm #build RPM

Publish sdist to PyPI

pip install twine
pyb package -E linux-release
cd target/dist/fysom-$VERSION
./setup.py sdist
# requires .pypirc configuration, obviously
twine upload -r pypi dist/*

Looking at the coverage

pyb
cat target/reports/coverage

USAGE

Basics

1  from fysom import Fysom
2 
3  fsm = Fysom({ 'initial': 'green',
4                'events': [
5                    {'name': 'warn', 'src': 'green', 'dst': 'yellow'},
6                    {'name': 'panic', 'src': 'yellow', 'dst': 'red'},
7                    {'name': 'calm', 'src': 'red', 'dst': 'yellow'},
8                    {'name': 'clear', 'src': 'yellow', 'dst': 'green'} ] })

... will create an object with a method for each event:

  • fsm.warn() - transition from green to yellow
  • fsm.panic() - transition from yellow to red
  • fsm.calm() - transition from red to yellow
  • fsm.clear() - transition from yellow to green

along with the following members:

  • fsm.current - contains the current state
  • fsm.isstate(s) - return True if state s is the current state
  • fsm.can(e) - return True if event e can be fired in the current state
  • fsm.cannot(e) - return True if event s cannot be fired in the current state

Shorter Syntax

It's possible to define event transitions as 3-tuples (event name, source state, destination state) rather than dictionaries. Fysom constructor accepts also keyword arguments initial, events, callbacks, and final.

This is a shorter version of the previous example:

1  fsm = Fysom(initial='green',
2              events=[('warn',  'green',  'yellow'),
3                      ('panic', 'yellow', 'red'),
4                      ('calm',  'red',    'yellow'),
5                      ('clear', 'yellow', 'green')])

Initialization

How the state machine should initialize can depend on your application requirements, so the library provides a number of simple options.

By default, if you don't specify any initial state, the state machine will be in the none state and you would need to provide an event to take it out of this state:

1  fsm = Fysom({'events': [
2                  {'name': 'startup', 'src': 'none',  'dst': 'green'},
3                  {'name': 'panic', 'src': 'green', 'dst': 'red'},
4                  {'name': 'calm', 'src': 'red', 'dst': 'green'}]})
5  print fsm.current # "none"
6  fsm.startup()
7  print fsm.current # "green"

If you specify the name of your initial event (as in all the earlier examples), then an implicit startup event will be created for you and fired when the state machine is constructed:

1  fsm = Fysom({'initial': 'green',
2               'events': [
3                   {'name': 'panic', 'src': 'green', 'dst': 'red'},
4                   {'name': 'calm', 'src': 'red', 'dst': 'green'}]})
5  print fsm.current # "green"

If your object already has a startup method, you can use a different name for the initial event:

1  fsm = Fysom({'initial': {'state': 'green', 'event': 'init'},
2               'events': [
3                   {'name': 'panic', 'src': 'green', 'dst': 'red'},
4                   {'name': 'calm',  'src': 'red', 'dst': 'green'}]})
5  print fsm.current # "green"

Finally, if you want to wait to call the initial state transition event until a later date, you can defer it:

1  fsm = Fysom({'initial': {'state': 'green', 'event': 'init', 'defer': True},
2               'events': [
3                   {'name': 'panic', 'src': 'green', 'dst': 'red'},
4                   {'name': 'calm',  'src': 'red',   'dst': 'green'}]})
5  print fsm.current # "none"
6  fsm.init()
7  print fsm.current # "green"

Of course, we have now come full circle, this last example pretty much functions the same as the first example in this section where you simply define your own startup event.

So you have a number of choices available to you when initializing your state machine.

You can also indicate which state should be considered final. This has no effect on the state machine, but lets you use a shorthand method is_finished() that returns True if the state machine is in this final state:

 1  fsm = Fysom({'initial': 'green',
 2               'final': 'red',
 3               'events': [
 4                   {'name': 'panic', 'src': 'green', 'dst': 'red'},
 5                   {'name': 'calm',  'src': 'red',   'dst': 'green'}]})
 6  print fsm.current # "green"
 7  fsm.is_finished() # False
 8  fsm.panic()
 9  fsm.is_finished() # True

Dynamically generated event names

Sometimes you have to compute the name of an event you want to trigger on the fly. Instead of relying on getattr you can use the trigger method, which takes a string (the event name) as a parameter, followed by any arguments/keyword arguments you want to pass to the event method. This is also arguably better if you're not sure if the event exists at all (FysomError vs. AttributeError, see below).

 1  from fysom import Fysom
 2 
 3  fsm = Fysom({ 'initial': 'green',
 4                'events': [
 5                    {'name': 'warn', 'src': 'green', 'dst': 'yellow'},
 6                    {'name': 'panic', 'src': 'yellow', 'dst': 'red'},
 7                    {'name': 'calm', 'src': 'red', 'dst': 'yellow'},
 8                    {'name': 'clear', 'src': 'yellow', 'dst': 'green'} ] })
 9 
10  fsm.trigger('warn', msg="danger")  # equivalent to fsm.warn(msg="danger")
11  fsm.trigger('unknown')  # FysomError, event does not exist
12  fsm.unknown()  #  AttributeError, event does not exist

Multiple source and destination states for a single event

1  fsm = Fysom({'initial': 'hungry',
2               'events': [
3                   {'name': 'eat', 'src': 'hungry', 'dst': 'satisfied'},
4                   {'name': 'eat', 'src': 'satisfied', 'dst': 'full'},
5                   {'name': 'eat', 'src': 'full', 'dst': 'sick'},
6                   {'name': 'rest', 'src': ['hungry', 'satisfied', 'full', 'sick'], 'dst': 'hungry'}]})

This example will create an object with 2 event methods:

  • fsm.eat()
  • fsm.rest()

The rest event will always transition to the hungry state, while the eat event will transition to a state that is dependent on the current state.

NOTE the rest event in the above example can also be specified as multiple events with the same name if you prefer the verbose approach.

NOTE if an event can be triggered from any state, you can specify it using the * wildcard, or even by omitting the src attribute from its definition:

1  fsm = Fysom({'initial': 'hungry',
2               'events': [
3                   {'name': 'eat', 'src': 'hungry', 'dst': 'satisfied'},
4                   {'name': 'eat', 'src': 'satisfied', 'dst': 'full'},
5                   {'name': 'eat', 'src': 'full', 'dst': 'sick'},
6                   {'name': 'eat_a_lot', 'src': '*', 'dst': 'sick'},
7                   {'name': 'rest', 'dst': 'hungry'}]})

NOTE if an event will not change the current state, you can specify the destination using the = symbol. It's useful when using wildcard source or multiple sources:

 1  fsm = Fysom({'initial': 'hungry',
 2               'events': [
 3                   {'name': 'eat', 'src': 'hungry', 'dst': 'satisfied'},
 4                   {'name': 'eat', 'src': 'satisfied', 'dst': 'full'},
 5                   {'name': 'eat', 'src': 'full', 'dst': 'sick'},
 6                   {'name': 'eat_a_little', 'src': '*', 'dst': '='},
 7                   {'name': 'eat_a_little', 'src': ['full', 'satisfied'], 'dst': '='},
 8                   {'name': 'eat_a_little', 'src': 'hungry', 'dst': '='},
 9                   {'name': 'rest', 'dst': 'hungry'}]})

Callbacks

5 callbacks are available if your state machine has methods using the following naming conventions:

  • onbefore_event - fired before the event
  • onleave_state - fired when leaving the old state
  • onenter_state - fired when entering the new state
  • onreenter_state - fired when reentering the old state (a reflexive transition i.e. src == dst)
  • onafter_event - fired after the event

You can affect the event in 2 ways:

  • return False from an onbefore_event handler to cancel the event. This will raise a fysom.Canceled exception.
  • return False from an onleave_state handler to perform an asynchronous state transition (see next section).

For convenience, the 2 most useful callbacks can be shortened:

  • on_event - convenience shorthand for onafter_event
  • on_state - convenience shorthand for onenter_state

In addition, a generic onchangestate() callback can be used to call a single function for all state changes.

All callbacks will be passed one argument e which is an object with following attributes:

  • fsm - Fysom object calling the callback
  • event - Event name
  • src - Source state
  • dst - Destination state
  • (any other keyword arguments you passed into the original event method)
  • (any positional argument you passed in the original event method, in the args attribute of the event)

Note that when you call an event, only one instance of e argument is created and passed to all 4 callbacks. This allows you to preserve data across a state transition by storing it in e. It also allows you to shoot yourself in the foot if you're not careful.

Callbacks can be specified when the state machine is first created:

 1  def onpanic(e):
 2      print 'panic! ' + e.msg
 3  def oncalm(e):
 4      print 'thanks to ' + e.msg + ' done by ' + e.args[0]
 5  def ongreen(e):
 6      print 'green'
 7  def onyellow(e):
 8      print 'yellow'
 9  def onred(e):
10      print 'red'
11  fsm = Fysom({'initial': 'green',
12               'events': [
13                   {'name': 'warn', 'src': 'green', 'dst': 'yellow'},
14                   {'name': 'panic', 'src': 'yellow', 'dst': 'red'},
15                   {'name': 'panic', 'src': 'green', 'dst': 'red'},
16                   {'name': 'calm', 'src': 'red', 'dst': 'yellow'},
17                   {'name': 'clear', 'src': 'yellow', 'dst': 'green'}],
18               'callbacks': {
19                   'onpanic': onpanic,
20                   'oncalm': oncalm,
21                   'ongreen': ongreen,
22                   'onyellow': onyellow,
23                   'onred': onred }})
24 
25  fsm.panic(msg='killer bees')
26  fsm.calm('bob', msg='sedatives in the honey pots')

Additionally, they can be added and removed from the state machine at any time:

1  def printstatechange(e):
2      print 'event: %s, src: %s, dst: %s' % (e.event, e.src, e.dst)
3 
4  del fsm.ongreen
5  del fsm.onyellow
6  del fsm.onred
7  fsm.onchangestate = printstatechange

Asynchronous state transitions

Sometimes, you need to execute some asynchronous code during a state transition and ensure the new state is not entered until you code has completed.

A good example of this is when you run a background thread to download something as result of an event. You only want to transition into the new state after the download is complete.

You can return False from your onleave_state handler and the state machine will be put on hold until you are ready to trigger the transition using the transition() method.

Use as global machine

To manipulating lots of objects with a small memory footprint, there is a FysomGlobal class. Also a useful FysomGlobalMixin class to give convenience access for the state machine methods.

A use case is using with Django, which has a cache mechanism holds lots of model objects (database records) in memory, using global machine can save a lot of memory, here is a compare.

The basic usage is same with Fysom, with slight differences and enhancements:

  • Initial state will only be automatically triggered for class derived from FysomGlobalMixin. Or you need to trigger manually.
  • The snake_case python naming conversion is supported.
  • Conditions and conditional transitions are implemented.
  • When an event/transition is canceled, the event object will be attached to the raised fysom.Canceled exception. By doing this, additional information can be passed through the exception.

Usage example:

 1  class Model(FysomGlobalMixin, object):
 2      GSM = FysomGlobal(
 3          events=[('warn',  'green',  'yellow'),
 4                  {
 5                      'name': 'panic',
 6                      'src': ['green', 'yellow'],
 7                      'dst': 'red',
 8                      'cond': [  # can be function object or method name
 9                          'is_angry',  # by default target is "True"
10                          {True: 'is_very_angry', 'else': 'yellow'}
11                      ]
12                  },
13                  ('calm',  'red',    'yellow'),
14                  ('clear', 'yellow', 'green')],
15          initial='green',
16          final='red',
17          state_field='state'
18      )
19 
20      def __init__(self):
21          self.state = None
22          super(Model, self).__init__()
23 
24      def is_angry(self, event):
25          return True
26 
27      def is_very_angry(self, event):
28          return False
29 
30  obj = Model()
31  obj.current  # 'green'
32  obj.warn()
33  obj.is_state('yellow')  # True
34  # conditions and conditional transition
35  obj.panic()
36  obj.current  # 'yellow'
37  obj.is_finished()  # False

About

Finite State Machine for Python (based on Jake Gordon's javascript-state-machine)

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Python 100.0%