Skip to main content
Travis build status image Coverage status Latest PyPI version Number of PyPI downloads

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.3 and PyPy.

Installation

From your friendly neighbourhood cheeseshop

pip install fysom

Developer setup

This module uses the pybuilder.

sudo pip install pyb_init
pyb-init github mriehl : fysom

Running the tests

pyb verify

Generating and using a setup.py

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

Looking at the coverage

pyb
cat target/reports/coverage

USAGE

Basics

from fysom import Fysom

fsm = Fysom({ 'initial': 'green',
              'events': [
                  {'name': 'warn', 'src': 'green', 'dst': 'yellow'},
                  {'name': 'panic', 'src': 'yellow', 'dst': 'red'},
                  {'name': 'calm', 'src': 'red', 'dst': 'yellow'},
                  {'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

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:

fsm = Fysom({'events': [
                {'name': 'startup', 'src': 'none',  'dst': 'green'},
                {'name': 'panic', 'src': 'green', 'dst': 'red'},
                {'name': 'calm', 'src': 'red', 'dst': 'green'}]})
print fsm.current # "none"
fsm.startup()
print fsm.current # "green"

If you specifiy the name of you 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:

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

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

fsm = Fysom({'initial': {'state': 'green', 'event': 'init'},
             'events': [
                 {'name': 'panic', 'src': 'green', 'dst': 'red'},
                 {'name': 'calm',  'src': 'red', 'dst': 'green'}]})
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:

fsm = Fysom({'initial': {'state': 'green', 'event': 'init', 'defer': True},
             'events': [
                 {'name': 'panic', 'src': 'green', 'dst': 'red'},
                 {'name': 'calm',  'src': 'red',   'dst': 'green'}]})
print fsm.current # "none"
fsm.init()
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.

Multiple source and destination states for a single event

fsm = Fysom({'initial': 'hungry',
             'events': [
                 {'name': 'eat', 'src': 'hungry', 'dst': 'satisfied'},
                 {'name': 'eat', 'src': 'satisfied', 'dst': 'full'},
                 {'name': 'eat', 'src': 'full', 'dst': 'sick'},
                 {'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.

Callbacks

4 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

  • 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.

  • 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() calback 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:

def onpanic(e):
    print 'panic! ' + e.msg
def oncalm(e):
    print 'thanks to ' + e.msg + ' done by ' + e.args[0]
def ongreen(e):
    print 'green'
def onyellow(e):
    print 'yellow'
def onred(e):
    print 'red'
fsm = Fysom({'initial': 'green',
             'events': [
                 {'name': 'warn', 'src': 'green', 'dst': 'yellow'},
                 {'name': 'panic', 'src': 'yellow', 'dst': 'red'},
                 {'name': 'panic', 'src': 'green', 'dst': 'red'},
                 {'name': 'calm', 'src': 'red', 'dst': 'yellow'},
                 {'name': 'clear', 'src': 'yellow', 'dst': 'green'}],
             'callbacks': {
                 'onpanic': onpanic,
                 'oncalm': oncalm,
                 'ongreen': ongreen,
                 'onyellow': onyellow,
                 'onred': onred }})

fsm.panic(msg='killer bees')
fsm.calm('bob', msg='sedatives in the honey pots')

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

def printstatechange(e):
    print 'event: %s, src: %s, dst: %s' % (e.event, e.src, e.dst)

del fsm.ongreen
del fsm.onyellow
del fsm.onred
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.

Metadata

Release files for fysom 1.0.12

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fysom 1.0.12
File Size Uploaded Provenance Actions
fysom-1.0.12.tar.gz 5.7 kB Without provenance Details for fysom-1.0.12.tar.gz

Release files / fysom-1.0.12.tar.gz

Download URL fysom-1.0.12.tar.gz
Size 5.7 kB
Tags Source
SHA-256 checksum
How to use checksums
30027e3c2ffaaea3f5d3e33226830a5c59d6dd90f5ac014414eedeaa881713c6
BLAKE2b-256 checksum
How to use checksums
acb8fd5206d86bdd4aa533672e85606d76efb47143a0d3e39d2a1ebcc59890e8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Security for fysom 1.0.12

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page