Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Simple finite-state machines in Python

branch: master

Fetching latest commit…

Octocat-spinner-32-eaf2f5

Cannot retrieve the latest commit at this time

Octocat-spinner-32 examples
Octocat-spinner-32 tests
Octocat-spinner-32 .gitignore
Octocat-spinner-32 .travis.yml
Octocat-spinner-32 LICENSE
Octocat-spinner-32 README.md
Octocat-spinner-32 requirements.txt
Octocat-spinner-32 setup.py
Octocat-spinner-32 statemachine.py
README.md

statemachine

Build Status

If you aren't programming with state machines, you should be.

statemachine offers a simple and easy-to-use finite-state machine that can adapted into almost any code base.

Usage

To create a state machine, mix in the statemachine.Machine class. The only requirement is an initial state, which are represented as strings.

import statemachine

class TrafficLight(statemachine.Machine):
    initial_state = 'red'

This machine won't do much, but we can get the current state

>>> stoplight = TrafficLight()
>>> stoplight.state
'red'

We can add state transitions using the event decorator. These functions return an iterable of transitions. A transition is just a two-tuple. The first element is an iterable of states, the wilcard '*', or a single state. The second element is the target state.

import statemachine

class TrafficLight(statemachine.Machine):
    initial_state = 'red'

    @statemachine.event
    def cycle(self):
        yield 'red', 'green'
        yield 'green', 'yellow'
        yield 'yellow', 'red'

Calling the cycle method will transition the machine into the next state.

>>> stoplight = TrafficLight()
>>> stoplight.state
'red'
>>> stoplight.cycle()
>>> stoplight.state
'green'

You can listen for transition events using the before_transition and after_transition decorators`.

import statemachine

class TrafficLight(statemachine.Machine):
    initial_state = 'red'

    @statemachine.event
    def cycle(self):
        yield 'red', 'green'
        yield 'green', 'yellow'
        yield 'yellow', 'red'

    @statemachine.after_transition('red', 'green')
    def announce(self):
        print "GO GO GO"

Initiate the transition by calling cycle

>>> stoplight = TrafficLight()
>>> stoplight.cycle()
'GO GO GO'

If you only care about where you're coming from (or where you're going), use the transition_from and transition_to decorator

import statemachine

class TrafficLight(statemachine.Machine):
    initial_state = 'red'

    @statemachine.event
    def cycle(self):
        yield 'red', 'green'
        yield 'green', 'yellow'
        yield 'yellow', 'red'

    @transition_to('yellow')
    def safety(self):
        print "SLOW DOWN"

    @transition_from('red')
    def announce(self):
        print "GO GO GO"

Installation

$ pip install statemachine
Something went wrong with that request. Please try again.