automaton(1)

AUTOMATON(1) automaton AUTOMATON(1)

NAME

automaton - automaton 3.1.0

Friendly state machines for python.

AUTOMATON USER GUIDE

Features

Machines

  • A automaton.machines.FiniteMachine state machine.
  • A automaton.machines.HierarchicalFiniteMachine hierarchical state machine.

Runners

  • A automaton.runners.FiniteRunner state machine runner.
  • A automaton.runners.HierarchicalRunner hierarchical state machine runner.

Examples

Creating a simple machine

from automaton import machines
m = machines.FiniteMachine()
m.add_state('up')
m.add_state('down')
m.add_transition('down', 'up', 'jump')
m.add_transition('up', 'down', 'fall')
m.default_start_state = 'down'
print(m.pformat())


Expected output:

+---------+-------+------+----------+---------+
|  Start  | Event | End  | On Enter | On Exit |
+---------+-------+------+----------+---------+
| down[^] |  jump |  up  |    .     |    .    |
|    up   |  fall | down |    .     |    .    |
+---------+-------+------+----------+---------+


Transitioning a simple machine

m.initialize()
m.process_event('jump')
print(m.pformat())
print(m.current_state)
print(m.terminated)
m.process_event('fall')
print(m.pformat())
print(m.current_state)
print(m.terminated)


Expected output:

+---------+-------+------+----------+---------+
|  Start  | Event | End  | On Enter | On Exit |
+---------+-------+------+----------+---------+
| down[^] |  jump |  up  |    .     |    .    |
|   @up   |  fall | down |    .     |    .    |
+---------+-------+------+----------+---------+
up
False
+----------+-------+------+----------+---------+
|  Start   | Event | End  | On Enter | On Exit |
+----------+-------+------+----------+---------+
| @down[^] |  jump |  up  |    .     |    .    |
|    up    |  fall | down |    .     |    .    |
+----------+-------+------+----------+---------+
down
False


Running a complex dog-barking machine

from automaton import machines
from automaton import runners
# These reaction functions will get triggered when the registered state
# and event occur, it is expected to provide a new event that reacts to the
# new stable state (so that the state-machine can transition to a new
# stable state, and repeat, until the machine ends up in a terminal
# state, whereby it will stop...)
def react_to_squirrel(old_state, new_state, event_that_triggered):

return "gets petted" def react_to_wagging(old_state, new_state, event_that_triggered):
return "gets petted" m = machines.FiniteMachine() m.add_state("sits") m.add_state("lies down", terminal=True) m.add_state("barks") m.add_state("wags tail") m.default_start_state = 'sits' m.add_transition("sits", "barks", "squirrel!") m.add_transition("barks", "wags tail", "gets petted") m.add_transition("wags tail", "lies down", "gets petted") m.add_reaction("barks", "squirrel!", react_to_squirrel) m.add_reaction('wags tail', "gets petted", react_to_wagging) print(m.pformat()) r = runners.FiniteRunner(m) for (old_state, new_state) in r.run_iter("squirrel!"):
print("Leaving '%s'" % old_state)
print("Entered '%s'" % new_state)


Expected output:

+--------------+-------------+-----------+----------+---------+
|    Start     |    Event    |    End    | On Enter | On Exit |
+--------------+-------------+-----------+----------+---------+
|    barks     | gets petted | wags tail |    .     |    .    |
| lies down[$] |      .      |     .     |    .     |    .    |
|   sits[^]    |  squirrel!  |   barks   |    .     |    .    |
|  wags tail   | gets petted | lies down |    .     |    .    |
+--------------+-------------+-----------+----------+---------+
Leaving 'sits'
Entered 'barks'
Leaving 'barks'
Entered 'wags tail'
Leaving 'wags tail'
Entered 'lies down'


Creating a complex CD-player machine

from automaton import machines
def print_on_enter(new_state, triggered_event):

print("Entered '%s' due to '%s'" % (new_state, triggered_event)) def print_on_exit(old_state, triggered_event):
print("Exiting '%s' due to '%s'" % (old_state, triggered_event)) m = machines.FiniteMachine() m.add_state('stopped', on_enter=print_on_enter, on_exit=print_on_exit) m.add_state('opened', on_enter=print_on_enter, on_exit=print_on_exit) m.add_state('closed', on_enter=print_on_enter, on_exit=print_on_exit) m.add_state('playing', on_enter=print_on_enter, on_exit=print_on_exit) m.add_state('paused', on_enter=print_on_enter, on_exit=print_on_exit) m.add_transition('stopped', 'playing', 'play') m.add_transition('stopped', 'opened', 'open_close') m.add_transition('stopped', 'stopped', 'stop') m.add_transition('opened', 'closed', 'open_close') m.add_transition('closed', 'opened', 'open_close') m.add_transition('closed', 'stopped', 'cd_detected') m.add_transition('playing', 'stopped', 'stop') m.add_transition('playing', 'paused', 'pause') m.add_transition('playing', 'opened', 'open_close') m.add_transition('paused', 'playing', 'play') m.add_transition('paused', 'stopped', 'stop') m.add_transition('paused', 'opened', 'open_close') m.default_start_state = 'closed' m.initialize() print(m.pformat()) for event in ['cd_detected', 'play', 'pause', 'play', 'stop',
'open_close', 'open_close']:
m.process_event(event)
print(m.pformat())
print("=============")
print("Current state => %s" % m.current_state)
print("=============")


Expected output:

+------------+-------------+---------+----------------+---------------+
|   Start    |    Event    |   End   |    On Enter    |    On Exit    |
+------------+-------------+---------+----------------+---------------+
| @closed[^] | cd_detected | stopped | print_on_enter | print_on_exit |
| @closed[^] |  open_close |  opened | print_on_enter | print_on_exit |
|   opened   |  open_close |  closed | print_on_enter | print_on_exit |
|   paused   |  open_close |  opened | print_on_enter | print_on_exit |
|   paused   |     play    | playing | print_on_enter | print_on_exit |
|   paused   |     stop    | stopped | print_on_enter | print_on_exit |
|  playing   |  open_close |  opened | print_on_enter | print_on_exit |
|  playing   |    pause    |  paused | print_on_enter | print_on_exit |
|  playing   |     stop    | stopped | print_on_enter | print_on_exit |
|  stopped   |  open_close |  opened | print_on_enter | print_on_exit |
|  stopped   |     play    | playing | print_on_enter | print_on_exit |
|  stopped   |     stop    | stopped | print_on_enter | print_on_exit |
+------------+-------------+---------+----------------+---------------+
Exiting 'closed' due to 'cd_detected'
Entered 'stopped' due to 'cd_detected'
+-----------+-------------+---------+----------------+---------------+
|   Start   |    Event    |   End   |    On Enter    |    On Exit    |
+-----------+-------------+---------+----------------+---------------+
| closed[^] | cd_detected | stopped | print_on_enter | print_on_exit |
| closed[^] |  open_close |  opened | print_on_enter | print_on_exit |
|   opened  |  open_close |  closed | print_on_enter | print_on_exit |
|   paused  |  open_close |  opened | print_on_enter | print_on_exit |
|   paused  |     play    | playing | print_on_enter | print_on_exit |
|   paused  |     stop    | stopped | print_on_enter | print_on_exit |
|  playing  |  open_close |  opened | print_on_enter | print_on_exit |
|  playing  |    pause    |  paused | print_on_enter | print_on_exit |
|  playing  |     stop    | stopped | print_on_enter | print_on_exit |
|  @stopped |  open_close |  opened | print_on_enter | print_on_exit |
|  @stopped |     play    | playing | print_on_enter | print_on_exit |
|  @stopped |     stop    | stopped | print_on_enter | print_on_exit |
+-----------+-------------+---------+----------------+---------------+
=============
Current state => stopped
=============
Exiting 'stopped' due to 'play'
Entered 'playing' due to 'play'
+-----------+-------------+---------+----------------+---------------+
|   Start   |    Event    |   End   |    On Enter    |    On Exit    |
+-----------+-------------+---------+----------------+---------------+
| closed[^] | cd_detected | stopped | print_on_enter | print_on_exit |
| closed[^] |  open_close |  opened | print_on_enter | print_on_exit |
|   opened  |  open_close |  closed | print_on_enter | print_on_exit |
|   paused  |  open_close |  opened | print_on_enter | print_on_exit |
|   paused  |     play    | playing | print_on_enter | print_on_exit |
|   paused  |     stop    | stopped | print_on_enter | print_on_exit |
|  @playing |  open_close |  opened | print_on_enter | print_on_exit |
|  @playing |    pause    |  paused | print_on_enter | print_on_exit |
|  @playing |     stop    | stopped | print_on_enter | print_on_exit |
|  stopped  |  open_close |  opened | print_on_enter | print_on_exit |
|  stopped  |     play    | playing | print_on_enter | print_on_exit |
|  stopped  |     stop    | stopped | print_on_enter | print_on_exit |
+-----------+-------------+---------+----------------+---------------+
=============
Current state => playing
=============
Exiting 'playing' due to 'pause'
Entered 'paused' due to 'pause'
+-----------+-------------+---------+----------------+---------------+
|   Start   |    Event    |   End   |    On Enter    |    On Exit    |
+-----------+-------------+---------+----------------+---------------+
| closed[^] | cd_detected | stopped | print_on_enter | print_on_exit |
| closed[^] |  open_close |  opened | print_on_enter | print_on_exit |
|   opened  |  open_close |  closed | print_on_enter | print_on_exit |
|  @paused  |  open_close |  opened | print_on_enter | print_on_exit |
|  @paused  |     play    | playing | print_on_enter | print_on_exit |
|  @paused  |     stop    | stopped | print_on_enter | print_on_exit |
|  playing  |  open_close |  opened | print_on_enter | print_on_exit |
|  playing  |    pause    |  paused | print_on_enter | print_on_exit |
|  playing  |     stop    | stopped | print_on_enter | print_on_exit |
|  stopped  |  open_close |  opened | print_on_enter | print_on_exit |
|  stopped  |     play    | playing | print_on_enter | print_on_exit |
|  stopped  |     stop    | stopped | print_on_enter | print_on_exit |
+-----------+-------------+---------+----------------+---------------+
=============
Current state => paused
=============
Exiting 'paused' due to 'play'
Entered 'playing' due to 'play'
+-----------+-------------+---------+----------------+---------------+
|   Start   |    Event    |   End   |    On Enter    |    On Exit    |
+-----------+-------------+---------+----------------+---------------+
| closed[^] | cd_detected | stopped | print_on_enter | print_on_exit |
| closed[^] |  open_close |  opened | print_on_enter | print_on_exit |
|   opened  |  open_close |  closed | print_on_enter | print_on_exit |
|   paused  |  open_close |  opened | print_on_enter | print_on_exit |
|   paused  |     play    | playing | print_on_enter | print_on_exit |
|   paused  |     stop    | stopped | print_on_enter | print_on_exit |
|  @playing |  open_close |  opened | print_on_enter | print_on_exit |
|  @playing |    pause    |  paused | print_on_enter | print_on_exit |
|  @playing |     stop    | stopped | print_on_enter | print_on_exit |
|  stopped  |  open_close |  opened | print_on_enter | print_on_exit |
|  stopped  |     play    | playing | print_on_enter | print_on_exit |
|  stopped  |     stop    | stopped | print_on_enter | print_on_exit |
+-----------+-------------+---------+----------------+---------------+
=============
Current state => playing
=============
Exiting 'playing' due to 'stop'
Entered 'stopped' due to 'stop'
+-----------+-------------+---------+----------------+---------------+
|   Start   |    Event    |   End   |    On Enter    |    On Exit    |
+-----------+-------------+---------+----------------+---------------+
| closed[^] | cd_detected | stopped | print_on_enter | print_on_exit |
| closed[^] |  open_close |  opened | print_on_enter | print_on_exit |
|   opened  |  open_close |  closed | print_on_enter | print_on_exit |
|   paused  |  open_close |  opened | print_on_enter | print_on_exit |
|   paused  |     play    | playing | print_on_enter | print_on_exit |
|   paused  |     stop    | stopped | print_on_enter | print_on_exit |
|  playing  |  open_close |  opened | print_on_enter | print_on_exit |
|  playing  |    pause    |  paused | print_on_enter | print_on_exit |
|  playing  |     stop    | stopped | print_on_enter | print_on_exit |
|  @stopped |  open_close |  opened | print_on_enter | print_on_exit |
|  @stopped |     play    | playing | print_on_enter | print_on_exit |
|  @stopped |     stop    | stopped | print_on_enter | print_on_exit |
+-----------+-------------+---------+----------------+---------------+
=============
Current state => stopped
=============
Exiting 'stopped' due to 'open_close'
Entered 'opened' due to 'open_close'
+-----------+-------------+---------+----------------+---------------+
|   Start   |    Event    |   End   |    On Enter    |    On Exit    |
+-----------+-------------+---------+----------------+---------------+
| closed[^] | cd_detected | stopped | print_on_enter | print_on_exit |
| closed[^] |  open_close |  opened | print_on_enter | print_on_exit |
|  @opened  |  open_close |  closed | print_on_enter | print_on_exit |
|   paused  |  open_close |  opened | print_on_enter | print_on_exit |
|   paused  |     play    | playing | print_on_enter | print_on_exit |
|   paused  |     stop    | stopped | print_on_enter | print_on_exit |
|  playing  |  open_close |  opened | print_on_enter | print_on_exit |
|  playing  |    pause    |  paused | print_on_enter | print_on_exit |
|  playing  |     stop    | stopped | print_on_enter | print_on_exit |
|  stopped  |  open_close |  opened | print_on_enter | print_on_exit |
|  stopped  |     play    | playing | print_on_enter | print_on_exit |
|  stopped  |     stop    | stopped | print_on_enter | print_on_exit |
+-----------+-------------+---------+----------------+---------------+
=============
Current state => opened
=============
Exiting 'opened' due to 'open_close'
Entered 'closed' due to 'open_close'
+------------+-------------+---------+----------------+---------------+
|   Start    |    Event    |   End   |    On Enter    |    On Exit    |
+------------+-------------+---------+----------------+---------------+
| @closed[^] | cd_detected | stopped | print_on_enter | print_on_exit |
| @closed[^] |  open_close |  opened | print_on_enter | print_on_exit |
|   opened   |  open_close |  closed | print_on_enter | print_on_exit |
|   paused   |  open_close |  opened | print_on_enter | print_on_exit |
|   paused   |     play    | playing | print_on_enter | print_on_exit |
|   paused   |     stop    | stopped | print_on_enter | print_on_exit |
|  playing   |  open_close |  opened | print_on_enter | print_on_exit |
|  playing   |    pause    |  paused | print_on_enter | print_on_exit |
|  playing   |     stop    | stopped | print_on_enter | print_on_exit |
|  stopped   |  open_close |  opened | print_on_enter | print_on_exit |
|  stopped   |     play    | playing | print_on_enter | print_on_exit |
|  stopped   |     stop    | stopped | print_on_enter | print_on_exit |
+------------+-------------+---------+----------------+---------------+
=============
Current state => closed
=============


Creating a complex CD-player machine (using a state-space)

This example is equivalent to the prior one but creates a machine in a more declarative manner. Instead of calling add_state and add_transition a explicit and declarative format can be used. For example to create the same machine:

from automaton import machines
def print_on_enter(new_state, triggered_event):

print("Entered '%s' due to '%s'" % (new_state, triggered_event)) def print_on_exit(old_state, triggered_event):
print("Exiting '%s' due to '%s'" % (old_state, triggered_event)) # This will contain all the states and transitions that our machine will # allow, the format is relatively simple and designed to be easy to use. state_space = [
{
'name': 'stopped',
'next_states': {
# On event 'play' transition to the 'playing' state.
'play': 'playing',
'open_close': 'opened',
'stop': 'stopped',
},
'on_enter': print_on_enter,
'on_exit': print_on_exit,
},
{
'name': 'opened',
'next_states': {
'open_close': 'closed',
},
'on_enter': print_on_enter,
'on_exit': print_on_exit,
},
{
'name': 'closed',
'next_states': {
'open_close': 'opened',
'cd_detected': 'stopped',
},
'on_enter': print_on_enter,
'on_exit': print_on_exit,
},
{
'name': 'playing',
'next_states': {
'stop': 'stopped',
'pause': 'paused',
'open_close': 'opened',
},
'on_enter': print_on_enter,
'on_exit': print_on_exit,
},
{
'name': 'paused',
'next_states': {
'play': 'playing',
'stop': 'stopped',
'open_close': 'opened',
},
'on_enter': print_on_enter,
'on_exit': print_on_exit,
}, ] m = machines.FiniteMachine.build(state_space) m.default_start_state = 'closed' print(m.pformat())


Expected output:

+-----------+-------------+---------+----------------+---------------+
|   Start   |    Event    |   End   |    On Enter    |    On Exit    |
+-----------+-------------+---------+----------------+---------------+
| closed[^] | cd_detected | stopped | print_on_enter | print_on_exit |
| closed[^] |  open_close |  opened | print_on_enter | print_on_exit |
|   opened  |  open_close |  closed | print_on_enter | print_on_exit |
|   paused  |  open_close |  opened | print_on_enter | print_on_exit |
|   paused  |     play    | playing | print_on_enter | print_on_exit |
|   paused  |     stop    | stopped | print_on_enter | print_on_exit |
|  playing  |  open_close |  opened | print_on_enter | print_on_exit |
|  playing  |    pause    |  paused | print_on_enter | print_on_exit |
|  playing  |     stop    | stopped | print_on_enter | print_on_exit |
|  stopped  |  open_close |  opened | print_on_enter | print_on_exit |
|  stopped  |     play    | playing | print_on_enter | print_on_exit |
|  stopped  |     stop    | stopped | print_on_enter | print_on_exit |
+-----------+-------------+---------+----------------+---------------+


NOTE:

As can be seen the two tables from this example and the prior one are exactly the same.


CHANGES

3.1.0

  • Add Python3 antelope unit tests
  • Update master for stable/zed

3.0.1

Fix formatting of release list

3.0.0

  • Drop python3.6/3.7 support in testing runtime
  • Remove unnecessary unicode prefixes
  • Add Python3 zed unit tests
  • Update master for stable/yoga

2.5.0

  • doc: Avoid duplicate entry warning
  • Add Python3 yoga unit tests
  • Update master for stable/xena

2.4.0

  • Moving to OFTC
  • setup.cfg: Replace dashes with underscores
  • Move flake8 as a pre-commit local target
  • Add Python3 xena unit tests
  • Update master for stable/wallaby
  • tox: Remove references to testr
  • Remove lower-constraints remnants

2.3.0

  • Uncap PrettyTable
  • Dropping lower constraints testing
  • Remove six dependency
  • Use TOX_CONSTRAINTS_FILE
  • Use py3 as the default runtime for tox
  • Adding pre-commit
  • Add Python3 wallaby unit tests
  • Update master for stable/victoria

2.2.0

  • Update lower-constraints list
  • drop mock from lower-constraints

2.1.0

  • Stop to use the __future__ module
  • Small cleanup
  • Switch to newer openstackdocstheme and reno versions
  • Bump default tox env from py37 to py38
  • Add py38 package metadata
  • Add Python3 victoria unit tests
  • Update master for stable/ussuri

2.0.1

Update hacking for Python3

2.0.0

  • Add python3 classifiers
  • Ignore releasenote artifacts files
  • [ussuri][goal] Drop python 2.7 support and testing
  • trivial: Remove noise
  • Move doc requirements into dedicated file
  • Switch to Ussuri jobs
  • Blacklist sphinx 2.1.0 (autodoc bug)
  • Update the constraints url
  • Update master for stable/train

1.17.0

  • Add Python 3 Train unit tests
  • Add local bindep.txt
  • Sync Sphinx requirement
  • Update to opendev
  • OpenDev Migration Patch
  • Update master for stable/stein
  • add python 3.7 unit test job

1.16.0

  • Use template for lower-constraints
  • Change openstack-dev to openstack-discuss
  • Change openstack-dev to openstack-discuss
  • add lib-forward-testing-python3 test job
  • add python 3.6 unit test job
  • import zuul job settings from project-config
  • Update reno for stable/rocky

1.15.0

  • Switch to stestr
  • fix tox python3 overrides
  • Trivial: Update pypi url to new url
  • fix list of default virtualenvs
  • set default python to python3
  • add lower-constraints job
  • Updated from global requirements
  • Update reno for stable/queens
  • Updated from global requirements
  • Updated from global requirements
  • Updated from global requirements

1.14.0

1.13.1

  • Avoid tox_install.sh for constraints support
  • Remove setting of version/release from releasenotes
  • Updated from global requirements

1.13.0

  • Updated from global requirements
  • Remove kwarg default_start_state in the machine constructor
  • Updated from global requirements
  • Update reno for stable/pike
  • Updated from global requirements

1.12.0

  • Update URLs in documents according to document migration
  • update link to docs in readme

1.11.0

  • switch from oslosphinx to openstackdocstheme
  • rearrange existing documentation according to the new standard layout
  • Updated from global requirements

1.10.0

  • Remove pbr warnerrors in favor of sphinx check
  • Remove support for py34
  • Updated from global requirements
  • Updated from global requirements

1.9.0

  • Updated from global requirements
  • Remove unused dependecy testscenarios

1.8.0

  • Updated from global requirements
  • Updated from global requirements
  • Update reno for stable/ocata

1.7.0

  • Don't include openstack/common in flake8 exclude list
  • Removes unnecessary utf-8 encoding
  • Add Constraints support
  • Replace six.iteritems() with .items()

1.6.0

  • Updated from global requirements
  • Fix release notes gate failure
  • Updated from global requirements
  • Add reno for release notes management

1.5.0

  • Changed the home-page link
  • Updated from global requirements
  • Updated from global requirements

1.4.0

  • Remove discover from test-requirements
  • Add Python 3.5 classifier and venv

1.3.0

Updated from global requirements

1.2.0

  • Add a state-space machine building example
  • Ensure state space can also pass on_enter/exit callbacks
  • Updated from global requirements
  • Updated from global requirements
  • Ensure machine special method(s) include in generated docs
  • Put py34 first in the envlist order of tox ,remove py33

1.1.0

  • Removes MANIFEST.in as it is not needed explicitely by PBR
  • Deprecated tox -downloadcache option removed

1.0.0

  • Updated from global requirements
  • Remove python 2.6 and cleanup tox.ini

0.8.0

  • Added code coverage section to tox
  • No need for Oslo Incubator Sync
  • Ignore generated files
  • docs - Set pbr 'warnerrors' option for doc build
  • Remove dummy/placeholder 'ChangeLog' as its not needed
  • Enhance the README
  • Fix the build path in .gitignore file
  • Updated from global requirements
  • Provide a finite machine build() method
  • Allow for raising on duplicate transition registration

0.7.0

  • Updated from global requirements
  • Updated from global requirements
  • Updated from global requirements

0.6.0

  • Activate pep8 check that _ is imported
  • Updated from global requirements

0.5.0

  • Ensure doctesting and doc8 testing done in py27 env
  • Updated from global requirements
  • Remove setup.cfg 'requires-python' incorrect entry
  • Document `process_event` return and expose return namedtuple type
  • Allow providing and using a 'nested_start_state_fetcher'
  • Allow providing a state-name translation dict

0.4.0

  • Add a bigger CD-player state-machine doctest(ed) example
  • Add `is_actionable_event` checking function
  • Disallow adding transitions from terminal states
  • Add and use a callback name fetching utility function
  • Add runners to features.rst & add a runner base & update docstrings

0.3.0

  • Add badge support to README.rst
  • Add code repo, mail list, and IRC to CONTRIBUTING
  • Remove 3.3 classifier
  • Remove 2.6 classifier + 2.6 compatibility code
  • Add history.rst that uses generated 'ChangeLog' file
  • Add base exception class for this library
  • Updated from global requirements
  • Add optional machine conversion into a pydot graph
  • Updated from global requirements
  • Updated from global requirements
  • When a state has no transitions show its own `on_exit` and `on_enter`
  • Add a more complex doctest(ed) example
  • Add simple machine doctest(ed) example into docs

0.2.0

  • Split the state machine runners off into own file
  • Use debtcollector removals function instead of warnings.warn
  • Revamp repo to match openstack repos
  • Allow the hierarchical machine to provide back the nested machines
  • Retain & deprecate default_start_state via constructor
  • Amend the unittest due to more on_exit being triggered
  • Have the start state 'on_exit' be called when exit occurs
  • Use a property setter instead of a method
  • Require using set_default_start_state to set the default
  • Add more checks on setting a alternative start state default
  • Rename start_state to default_start_state
  • Use type(self) instead of self.__class__
  • Correctly copy derived classes
  • Allow initialize to take an alternative start_state
  • Update message when processing event and not initialized
  • Add pre and post event processing methods
  • Share the same not found template between machines
  • Avoid having a _generate_runner method when inheritance is ok
  • Allow frozen to be set/unset
  • Add testrepository to testing requirements
  • Fixup the classifiers
  • Fix the tox to install the right requirements
  • Just use _generate_runner to generate the different runner types
  • Use quoting in the machine code documentation
  • Adjust pformat() + add examples
  • Remove version caps
  • Split the requirements file into py2/py3 variations
  • Move process event to be a static method
  • Add a HierarchicalFiniteMachine + Runner
  • Use a helper classmethod to create machines
  • Rename _Runner -> _FiniteRunner
  • Move to top level machines module, seems cleaner this way
  • Fix the pformat() example
  • Move the fsm -> machines/finite.py and split off the running methods
  • Allow copies to be unfrozen (if the parent is frozen)
  • Make frozen a non-settable attribute and copy it correctly
  • Allow machines to be shallow or deep copied
  • Three is the number for alpha
  • Change beta to alpha (for now)

0.1

  • Add the travis badge
  • Add a travis testing file
  • Also install the main requirements.txt when using tox
  • Move over the fsm test
  • Add testtools testing requirement
  • Use the test-requirements.txt for tox.ini deps
  • Add needed testing requirement and tox.ini file
  • Don't forget the requirements.txt file
  • Fixup the README.rst and setup.cfg
  • Use prettytable
  • Move a bunch of files into there rightful places
  • Initial commit

API

Machines

class automaton.machines.State(name, is_terminal=False, next_states=None, on_enter=None, on_exit=None)
Container that defines needed components of a single state.

Usage of this and the build() make creating finite state machines that much easier.

Variables
  • name -- The name of the state.
  • is_terminal -- Whether this state is terminal (or not).
  • next_states -- Dictionary of 'event' -> 'next state name' (or none).
  • on_enter -- callback that will be called when the state is entered.
  • on_exit -- callback that will be called when the state is exited.



class automaton.machines.FiniteMachine
A finite state machine.

This state machine can be used to automatically run a given set of transitions and states in response to events (either from callbacks or from generator/iterator send() values, see PEP 342). On each triggered event, a on_enter and on_exit callback can also be provided which will be called to perform some type of action on leaving a prior state and before entering a new state.

NOTE(harlowja): reactions will only be called when the generator/iterator from run_iter() does not send back a new event (they will always be called if the run() method is used). This allows for two unique ways (these ways can also be intermixed) to use this state machine when using run(); one where external event trigger the next state transition and one where internal reaction callbacks trigger the next state transition. The other way to use this state machine is to skip using run() or run_iter() completely and use the process_event() method explicitly and trigger the events via some external functionality/triggers...

class Effect(reaction, terminal)
The result of processing an event (cause and effect...)
reaction
Alias for field number 0

terminal
Alias for field number 1


__contains__(state)
Returns if this state exists in the machines known states.

__iter__()
Iterates over (start, event, end) transition tuples.

add_reaction(state, event, reaction, *args, **kwargs)
Adds a reaction that may get triggered by the given event & state.

Reaction callbacks may (depending on how the state machine is ran) be used after an event is processed (and a transition occurs) to cause the machine to react to the newly arrived at stable state.

These callbacks are expected to accept three default positional parameters (although more can be passed in via args and **kwargs, these will automatically get provided to the callback when it is activated *ontop of the three default). The three default parameters are the last stable state, the new stable state and the event that caused the transition to this new stable state to be arrived at.

The expected result of a callback is expected to be a new event that the callback wants the state machine to react to. This new event may (depending on how the state machine is ran) get processed (and this process typically repeats) until the state machine reaches a terminal state.


add_state(state, terminal=False, on_enter=None, on_exit=None)
Adds a given state to the state machine.

The on_enter and on_exit callbacks, if provided will be expected to take two positional parameters, these being the state being exited (for on_exit) or the state being entered (for on_enter) and a second parameter which is the event that is being processed that caused the state transition.


add_transition(start, end, event, replace=False)
Adds an allowed transition from start -> end for the given event.
Parameters
  • start -- starting state
  • end -- ending state
  • event -- event that causes start state to transition to end state
  • replace -- replace existing event instead of raising a Duplicate exception when the transition already exists.



classmethod build(state_space)
Builds a machine from a state space listing.

Each element of this list must be an instance of State or a dict with equivalent keys that can be used to construct a State instance.


copy(shallow=False, unfreeze=False)
Copies the current state machine.

NOTE(harlowja): the copy will be left in an uninitialized state.

NOTE(harlowja): when a shallow copy is requested the copy will share
the same transition table and state table as the source; this can be advantageous if you have a machine and transitions + states that is defined somewhere and want to use copies to run with (the copies have the current state that is different between machines).


property current_state
The current state the machine is in (or none if not initialized).

property default_start_state
Sets the default start state that the machine should use.

NOTE(harlowja): this will be used by initialize but only if that function is not given its own start_state that overrides this default.


property events
Returns how many events exist.

freeze()
Freezes & stops addition of states, transitions, reactions...

initialize(start_state=None)
Sets up the state machine (sets current state to start state...).
Parameters
start_state -- explicit start state to use to initialize the state machine to. If None is provided then the machine's default start state will be used instead.


is_actionable_event(event)
Check whether the event is actionable in the current state.

pformat(sort=True, empty='.')
Pretty formats the state + transition table into a string.

NOTE(harlowja): the sort parameter can be provided to sort the states and transitions by sort order; with it being provided as false the rows will be iterated in addition order instead.


process_event(event)
Trigger a state change in response to the provided event.
Returns
Effect this is either a FiniteMachine.Effect or an Effect from a subclass of FiniteMachine. See the appropriate named tuple for a description of the actual items in the tuple. For example, FiniteMachine.Effect's first item is reaction: one could invoke this reaction's callback to react to the new stable state.
Return type
namedtuple


property states
Returns the state names.

property terminated
Returns whether the state machine is in a terminal state.


class automaton.machines.HierarchicalFiniteMachine
A fsm that understands how to run in a hierarchical mode.
class Effect(reaction, terminal, machine)
The result of processing an event (cause and effect...)
machine
Alias for field number 2

reaction
Alias for field number 0

terminal
Alias for field number 1


add_state(state, terminal=False, on_enter=None, on_exit=None, machine=None)
Adds a given state to the state machine.
Parameters
machine (FiniteMachine) -- the nested state machine that will be transitioned into when this state is entered

Further arguments are interpreted as for FiniteMachine.add_state().


copy(shallow=False, unfreeze=False)
Copies the current state machine.

NOTE(harlowja): the copy will be left in an uninitialized state.

NOTE(harlowja): when a shallow copy is requested the copy will share
the same transition table and state table as the source; this can be advantageous if you have a machine and transitions + states that is defined somewhere and want to use copies to run with (the copies have the current state that is different between machines).


initialize(start_state=None, nested_start_state_fetcher=None)
Sets up the state machine (sets current state to start state...).
Parameters
  • start_state -- explicit start state to use to initialize the state machine to. If None is provided then the machine's default start state will be used instead.
  • nested_start_state_fetcher -- A callback that can return start states for any nested machines only. If not None then it will be provided a single argument, the machine to provide a starting state for and it is expected to return a starting state (or None) for each machine called with. Do note that this callback will also be passed to other nested state machines as well, so it will also be used to initialize any state machines they contain (recursively).



property nested_machines
Dictionary of all nested state machines this machine may use.


Runners

class automaton.runners.Runner(machine)
Machine runner used to run a state machine.

Only one runner per machine should be active at the same time (aka there should not be multiple runners using the same machine instance at the same time).

abstract run(event, initialize=True)
Runs the state machine, using reactions only.

abstract run_iter(event, initialize=True)
Returns a iterator/generator that will run the state machine.

NOTE(harlowja): only one runner iterator/generator should be active for a machine, if this is not observed then it is possible for initialization and other local state to be corrupted and cause issues when running...



class automaton.runners.FiniteRunner(machine)
Finite machine runner used to run a finite machine.

Only one runner per machine should be active at the same time (aka there should not be multiple runners using the same machine instance at the same time).

run(event, initialize=True)
Runs the state machine, using reactions only.

run_iter(event, initialize=True)
Returns a iterator/generator that will run the state machine.

NOTE(harlowja): only one runner iterator/generator should be active for a machine, if this is not observed then it is possible for initialization and other local state to be corrupted and cause issues when running...



class automaton.runners.HierarchicalRunner(machine)
Hierarchical machine runner used to run a hierarchical machine.

Only one runner per machine should be active at the same time (aka there should not be multiple runners using the same machine instance at the same time).

run(event, initialize=True)
Runs the state machine, using reactions only.

run_iter(event, initialize=True)
Returns a iterator/generator that will run the state machine.

This will keep a stack (hierarchy) of machines active and jumps through them as needed (depending on which machine handles which event) during the running lifecycle.

NOTE(harlowja): only one runner iterator/generator should be active for a machine hierarchy, if this is not observed then it is possible for initialization and other local state to be corrupted and causes issues when running...



Converters

automaton.converters.pydot.convert(machine, graph_name, graph_attrs=None, node_attrs_cb=None, edge_attrs_cb=None, add_start_state=True, name_translations=None)
Translates the state machine into a pydot graph.
Parameters
  • machine (FiniteMachine) -- state machine to convert
  • graph_name (string) -- name of the graph to be created
  • graph_attrs (dict) -- any initial graph attributes to set (see http://www.graphviz.org/doc/info/attrs.html for what these can be)
  • node_attrs_cb (callback) -- a callback that takes one argument state and is expected to return a dict of node attributes (see http://www.graphviz.org/doc/info/attrs.html for what these can be)
  • edge_attrs_cb (callback) -- a callback that takes three arguments start_state, event, end_state and is expected to return a dict of edge attributes (see http://www.graphviz.org/doc/info/attrs.html for what these can be)
  • add_start_state (bool) -- when enabled this creates a private start state with the name __start__ that will be a point node that will have a dotted edge to the default_start_state that your machine may have defined (if your machine has no actively defined default_start_state then this does nothing, even if enabled)
  • name_translations (dict) -- a dict that provides alternative state string names for each state



Exceptions

exception automaton.exceptions.AutomatonException
Base class for most exceptions emitted from this library.

exception automaton.exceptions.Duplicate
Raised when a duplicate entry is found.

exception automaton.exceptions.FrozenMachine
Exception raised when a frozen machine is modified.

exception automaton.exceptions.InvalidState
Raised when a invalid state transition is attempted while executing.

exception automaton.exceptions.NotFound
Raised when some entry in some object doesn't exist.

exception automaton.exceptions.NotInitialized
Error raised when an action is attempted on a not inited machine.

Hierarchy

INSTALLATION

At the command line:

$ pip install automaton


Or, if you have virtualenvwrapper installed:

$ mkvirtualenv automaton
$ pip install automaton


CONTRIBUTING

If you would like to contribute to the development of OpenStack, you must follow the steps in this page:

https://docs.openstack.org/infra/manual/developers.html


If you already have a good understanding of how the system works and your OpenStack accounts are set up, you can skip to the development workflow section of this documentation to learn how changes to OpenStack should be submitted for review via the Gerrit tool:

https://docs.openstack.org/infra/manual/developers.html#development-workflow


The code is hosted at:

https://opendev.org/openstack/automaton.


Pull requests submitted through GitHub will be ignored.

Bugs should be filed on Launchpad, not GitHub:

https://bugs.launchpad.net/automaton


The mailing list is (prefix subjects with "[Oslo][Automaton]"):

https://lists.openstack.org/cgi-bin/mailman/listinfo/openstack-discuss


Questions and discussions take place in #openstack-oslo on irc.OFTC.net.

Indices and tables

  • Index
  • Module Index
  • Search Page

AUTHOR

unknown

COPYRIGHT

2023, OpenStack Foundation

October 16, 2023 3.1.0