tfism 0.9.5.post4
A lightweight, object-oriented Python state machine implementation with many extensions.
License: MIT
Requires Python: >=3.10
Keywords: finite state machine, fsm, state machine, statemachine

# <a name="transitions-module"></a> tfism

[![Version](https://img.shields.io/badge/version-v0.9.5.post4-orange.svg)](https://github.com/pytransitions/tfism)
[![Build Status](https://github.com/pytransitions/tfism/actions/workflows/pytest.yml/badge.svg)](https://github.com/pytransitions/tfism/actions?query=workflow%3Apytest)
[![Coverage Status](https://coveralls.io/repos/github/pytransitions/tfism/badge.svg?branch=main)](https://coveralls.io/github/pytransitions/tfism?branch=main)
[![PyPi](https://img.shields.io/pypi/v/tfism.svg)](https://pypi.org/project/tfism)
[![Copr](https://img.shields.io/badge/dynamic/json?color=blue&label=copr&query=builds.latest.source_package.version&url=https%3A%2F%2Fcopr.fedorainfracloud.org%2Fapi_3%2Fpackage%3Fownername%3Daleneum%26projectname%3Dpython-tfism%26packagename%3Dpython-tfism%26with_latest_build%3DTrue)](https://copr.fedorainfracloud.org/coprs/aleneum/python-tfism/)
[![GitHub commits](https://img.shields.io/github/commits-since/pytransitions/tfism/0.9.5.svg)](https://github.com/pytransitions/tfism/compare/0.9.5.post4...main)
[![License](https://img.shields.io/github/license/pytransitions/tfism.svg)](LICENSE)
[![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/pytransitions/tfism/main?filepath=examples%2FPlayground.ipynb)

<!-- [![Pylint](https://img.shields.io/badge/pylint-9.71%2F10-green.svg)](https://github.com/pytransitions/transitions) -->
<!--[![Name](Image)](Link)-->

A lightweight, object-oriented state machine implementation in Python with many extensions. **Requires Python 3.11+**.

## Installation

### Using pip (recommended)

    pip install tfism

### Using uv (faster, modern package manager)

    # Install uv first (if you haven't already)
    curl -LsSf https://astral.sh/uv/install.sh | sh

    # Install tfism
    uv pip install tfism

### From source

    git clone https://github.com/pytransitions/tfism.git
    cd tfism
    uv pip install -e .  # or: pip install -e .

## Table of Contents

- [Quickstart](#quickstart)
- [Non-Quickstart](#the-non-quickstart)
  - [Some key concepts](#some-key-concepts)
  - [Basic initialization](#basic-initialization)
  - [States](#states)
    - [Callbacks](#state-callbacks)
    - [Checking state](#checking-state)
    - [Enumerations](#enum-state)
  - [Transitions](#transitions)
    - [Triggering a transition](#triggers)
    - [Automatic transitions](#automatic-transitions-for-all-states)
    - [Transitioning from multiple states](#transitioning-from-multiple-states)
    - [Reflexive transitions from multiple states](#reflexive-from-multiple-states)
    - [Internal transitions](#internal-transitions)
    - [Ordered transitions](#ordered-transitions)
    - [Queued transitions](#queued-transitions)
    - [Conditional transitions](#conditional-transitions)
    - [Check transitions](#check-transitions)
    - [Callbacks](#transition-callbacks)
  - [Callable resolution](#resolution)
  - [Callback execution order](#execution-order)
  - [Passing data](#passing-data)
  - [Alternative initialization patterns](#alternative-initialization-patterns)
  - [Logging](#logging)
  - [(Re-)Storing machine instances](#restoring)
  - [Typing support](#typing-support)
  - [Extensions](#extensions)
    - [Hierarchical State Machine](#hsm)
    - [Diagrams](#diagrams)
    - [Threading](#threading)
    - [Async](#async)
    - [State features](#state-features)
    - [Django](#django-support)
  - [Bug reports etc.](#bug-reports)

## Quickstart

They say [a good example is worth](https://www.google.com/webhp?ie=UTF-8#q=%22a+good+example+is+worth%22&start=20) 100 pages of API documentation, a million directives, or a thousand words.

Well, "they" probably lie... but here's an example anyway:

```python
from tfism import Machine
import random


class NarcolepticSuperhero(object):
    # Define some states. Most of the time, narcoleptic superheroes are just like
    # everyone else. Except for...
    states = ['asleep', 'hanging out', 'hungry', 'sweaty', 'saving the world']

    def __init__(self, name):
        # No anonymous superheroes on my watch! Every narcoleptic superhero gets
        # a name. Any name at all. SleepyMan. SlumberGirl. You get the idea.
        self.name = name

        # What have we accomplished today?
        self.kittens_rescued = 0

        # Initialize the state machine
        self.machine = Machine(model = self, states = NarcolepticSuperhero.states, initial = 'asleep')

        # Add some tfism. We could also define these using a static list of
        # dictionaries, as we did with states above, and then pass the list to
        # the Machine initializer as the tfism= argument.

        # At some point, every superhero must rise and shine.
        self.machine.add_transition(trigger = 'wake_up', source = 'asleep', dest = 'hanging out')

        # Superheroes need to keep in shape.
        self.machine.add_transition('work_out', 'hanging out', 'hungry')

        # Those calories won't replenish themselves!
        self.machine.add_transition('eat', 'hungry', 'hanging out')

        # Superheroes are always on call. ALWAYS. But they're not always
        # dressed in work-appropriate clothing.
        self.machine.add_transition('distress_call', '*', 'saving the world',
                                    before = 'change_into_super_secret_costume')

        # When they get off work, they're all sweaty and disgusting. But before
        # they do anything else, they have to meticulously log their latest
        # escapades. Because the legal department says so.
        self.machine.add_transition('complete_mission', 'saving the world', 'sweaty',
                                    after = 'update_journal')

        # Sweat is a disorder that can be remedied with water.
        # Unless you've had a particularly long day, in which case... bed time!
        self.machine.add_transition('clean_up', 'sweaty', 'asleep', conditions = ['is_exhausted'])
        self.machine.add_transition('clean_up', 'sweaty', 'hanging out')

        # Our NarcolepticSuperhero can fall asleep at pretty much any time.
        self.machine.add_transition('nap', '*', 'asleep')

    def update_journal(self):
        """ Dear Diary, today I saved Mr. Whiskers. Again. """
        self.kittens_rescued += 1

    @property
    def is_exhausted(self):
        """ Basically a coin toss. """
        return random.random() < 0.5

    def change_into_super_secret_costume(self):
        print("Beauty, eh?")
```

There, now you've baked a state machine into `NarcolepticSuperhero`. Let's take him/her/it out for a spin...

```python
>>> batman = NarcolepticSuperhero("Batman")
>>> batman.state
'asleep'

>>> batman.wake_up()
>>> batman.state
'hanging out'

>>> batman.nap()
>>> batman.state
'asleep'

>>> batman.clean_up()
MachineError: "Can't trigger event clean_up from state asleep!"

>>> batman.wake_up()
>>> batman.work_out()
>>> batman.state
'hungry'

# Batman still hasn't done anything useful...
>>> batman.kittens_rescued
0

# We now take you live to the scene of a horrific kitten entreement...
>>> batman.distress_call()
'Beauty, eh?'
>>> batman.state
'saving the world'

# Back to the crib.
>>> batman.complete_mission()
>>> batman.state
'sweaty'

>>> batman.clean_up()
>>> batman.state
'asleep'   # Too tired to shower!

# Another productive day, Alfred.
>>> batman.kittens_rescued
1
```

While we cannot read the mind of the actual batman, we surely can visualize the current state of our `NarcolepticSuperhero`.

![batman diagram](https://user-images.githubusercontent.com/205986/104932302-c2f24580-59a7-11eb-8963-5dce738b9305.png)

Have a look at the [Diagrams](#diagrams) extensions if you want to know how.

## The non-quickstart

A state machine is a _model_ of behavior composed of a finite number of _states_ and _transitions_ between those states. Within each state and transition some _action_ can be performed. A state machine needs to start at some _initial state_. When using `tfism`, a state machine may consist of multiple objects where some (_machines_) contain definitions for the manipulation of other (_models_). Below, we will look at some core concepts and how to work with them.

### Some key concepts

- **State**. A state represents a particular condition or stage in the state machine. It's a distinct mode of behavior or phase in a process.

- **Transition**. This is the process or event that causes the state machine to change from one state to another.

- **Model**. The actual stateful structure. It's the entity that gets updated during transitions. It may also define _actions_ that will be executed during transitions. For instance, right before a transition or when a state is entered or exited.

- **Machine**. This is the entity that manages and controls the model, states, transitions, and actions. It's the conductor that orchestrates the entire process of the state machine.

- **Trigger**. This is the event that initiates a transition, the method that sends the signal to start a transition.

- **Action**. Specific operation or task that is performed when a certain state is entered, exited, or during a transition. The action is implemented through _callbacks_, which are functions that get executed when some event happens.

### Basic initialization

Getting a state machine up and running is pretty simple. Let's say you have the object `lump` (an instance of class `Matter`), and you want to manage its states:

```python
class Matter(object):
    pass

lump = Matter()
```

You can initialize a (_minimal_) working state machine bound to the model `lump` like this:

```python
from tfism import Machine

machine = Machine(model = lump, states = ['solid', 'liquid', 'gas', 'plasma'], initial = 'solid')

# Lump now has a new state attribute!
lump.state
>> > 'solid'
```

An alternative is to not explicitly pass a model to the `Machine` initializer:

```python

machine = Machine(states=['solid', 'liquid', 'gas', 'plasma'], initial='solid')

# The machine instance itself now acts as a model
machine.state
>>> 'solid'
```

Note that this time I did not pass the `lump` model as an argument. The first argument passed to `Machine` acts as a model. So when I pass something there, all the convenience functions will be added to the object. If no model is provided then the `machine` instance itself acts as a model.

When at the beginning I said "minimal", it was because while this state machine is technically operational, it doesn't actually _do_ anything. It starts in the `'solid'` state, but won't ever move into another state, because no transitions are defined... yet!

Let's try again.

```python
# The states
states=['solid', 'liquid', 'gas', 'plasma']

# And some tfism between states. We're lazy, so we'll leave out
# the inverse phase tfism (freezing, condensation, etc.).
transitions = [
    { 'trigger': 'melt', 'source': 'solid', 'dest': 'liquid' },
    { 'trigger': 'evaporate', 'source': 'liquid', 'dest': 'gas' },
    { 'trigger': 'sublimate', 'source': 'solid', 'dest': 'gas' },
    { 'trigger': 'ionize', 'source': 'gas', 'dest': 'plasma' }
]

# Initialize
machine = Machine(lump, states=states, transitions=transitions, initial='liquid')

# Now lump maintains state...
lump.state
>>> 'liquid'

# And that state can change...
# Either calling the shiny new trigger methods
lump.evaporate()
lump.state
>>> 'gas'

# Or by calling the trigger method directly
lump.trigger('ionize')
lump.state
>>> 'plasma'
```

Notice the shiny new methods attached to the `Matter` instance (`evaporate()`, `ionize()`, etc.).
Each method triggers the corresponding transition.
Transitions can also be triggered _dynamically_ by calling the `trigger()` method provided with the name of the transition, as shown above.
More on this in the [Triggering a transition](#triggers) section.


### <a name="states"></a>States

The soul of any good state machine (and of many bad ones, no doubt) is a set of states. Above, we defined the valid model states by passing a list of strings to the `Machine` initializer. But internally, states are actually represented as `State` objects.

You can initialize and modify States in a number of ways. Specifically, you can:

- pass a string to the `Machine` initializer giving the name(s) of the state(s), or
- directly initialize each new `State` object, or
- pass a dictionary with initialization arguments

The following snippets illustrate several ways to achieve the same goal:

```python
# import Machine and State class
from tfism import Machine, State

# Create a list of 3 states to pass to the Machine
# initializer. We can mix types; in this case, we
# pass one State, one string, and one dict.
states = [
    State(name = 'solid'),
    'liquid',
    {'name': 'gas'}
]
machine = Machine(lump, states)

# This alternative example illustrates more explicit
# addition of states and state callbacks, but the net
# result is identical to the above.
machine = Machine(lump)
solid = State('solid')
liquid = State('liquid')
gas = State('gas')
machine.add_states([solid, liquid, gas])
```

States are initialized _once_ when added to the machine and will persist until they are removed from it. In other words: if you alter the attributes of a state object, this change will NOT be reset the next time you enter that state. Have a look at how to [extend state features](#state-features) in case you require some other behaviour.

#### <a name="state-callbacks"></a>Callbacks

But just having states and being able to move around between them (transitions) isn't very useful by itself. What if you want to do something, perform some _action_ when you enter or exit a state? This is where _callbacks_ come in.

A `State` can also be associated with a list of `enter` and `exit` callbacks, which are called whenever the state machine enters or leaves that state. You can specify callbacks during initialization by passing them to a `State` object constructor, in a state property dictionary, or add them later.

For convenience, whenever a new `State` is added to a `Machine`, the methods `on_enter_«state name»` and `on_exit_«state name»` are dynamically created on the Machine (not on the model!), which allow you to dynamically add new enter and exit callbacks later if you need them.

```python
# Our old Matter class, now with  a couple of new methods we
# can trigger when entering or exit states.
class Matter(object):
    def say_hello(self): print("hello, new state!")
    def say_goodbye(self): print("goodbye, old state!")

lump = Matter()

# Same states as above, but now we give StateA an exit callback
states = [
    State(name='solid', on_exit=['say_goodbye']),
    'liquid',
    { 'name': 'gas', 'on_exit': ['say_goodbye']}
    ]

machine = Machine(lump, states=states)
machine.add_transition('sublimate', 'solid', 'gas')

# Callbacks can also be added after initialization using
# the dynamically added on_enter_ and on_exit_ methods.
# Note that the initial call to add the callback is made
# on the Machine and not on the model.
machine.on_enter_gas('say_hello')

# Test out the callbacks...
machine.set_state('solid')
lump.sublimate()
>>> 'goodbye, old state!'
>>> 'hello, new state!'
```

Note that `on_enter_«state name»` callback will _not_ fire when a Machine is first initialized. For example if you have an `on_enter_A()` callback defined, and initialize the `Machine` with `initial='A'`, `on_enter_A()` will not be fired until the next time you enter state `A`. (If you need to make sure `on_enter_A()` fires at initialization, you can simply create a dummy initial state and then explicitly call `to_A()` inside the `__init__` method.)

In addition to passing in callbacks when initializing a `State`, or adding them dynamically, it's also possible to define callbacks in the model class itself, which may increase code clarity. For example:

```python
class Matter(object):
    def say_hello(self): print("hello, new state!")
    def say_goodbye(self): print("goodbye, old state!")
    def on_enter_A(self): print("We've just entered state A!")

lump = Matter()
machine = Machine(lump, states=['A', 'B', 'C'])
```

Now, any time `lump` transitions to state `A`, the `on_enter_A()` method defined in the `Matter` class will fire.

You can make use of `on_final` callbacks which will be triggered when a state with `final=True` is entered.

```python
from tfism import Machine, State

states = [State(name = 'idling'),
          State(name = 'rescuing_kitten'),
          State(name = 'offender_gone', final = True),
          State(name = 'offender_caught', final = True)]

transitions = [["called", "idling", "rescuing_kitten"],  # we will come when  called
               {"trigger": "intervene",
                "source": "rescuing_kitten",
                "dest": "offender_gone",  # we
                "conditions": "offender_is_faster"},  # unless they are faster
               ["intervene", "rescuing_kitten", "offender_caught"]]


class FinalSuperhero(object):

    def __init__(self, speed):
        self.machine = Machine(self, states = states, transitions = transitions, initial = "idling",
                               on_final = "claim_success")
        self.speed = speed

    def offender_is_faster(self, offender_speed):
        return self.speed < offender_speed

    def claim_success(self, **kwargs):
        print("The kitten is safe.")


hero = FinalSuperhero(speed = 10)  # we are not in shape today
hero.called()
assert hero.is_rescuing_kitten()
hero.intervene(offender_speed = 15)
# >>> 'The kitten is safe'
assert hero.machine.get_state(hero.state).final  # it's over
assert hero.is_offender_gone()  # maybe next time ...
```

#### <a name="state-pocket"></a>State Pocket

Have you ever wanted to get a return value from a state transition? For example, when transitioning to 'saving the world' state, wouldn't it be nice to know how many villains were defeated or how much time was spent?

**Problem:** State trigger functions don't have meaningful return values. This is because:
- Callbacks are executed in groups (before, prepare, on_enter, after, etc.)
- Complex calling chains exist with queued transitions and automatic state jumps
- It's unclear which callback's return value should be returned

**Solution:** Instead of complex return value collection, tfism provides a **"pocket"** feature - a temporary storage space on each State object where you can explicitly set values during the state's lifecycle.

The pocket is like a small pocket on the State object (named after the Pokemon concept) that can hold anything you want. The key characteristics are:

- **Explicit control**: You decide what goes into the pocket (usually in `on_enter` callbacks)
- **Automatic cleanup**: Pocket is automatically cleared when the state exits
- **State-scoped**: Each state has its own independent pocket
- **Type-flexible**: Can store any Python object (strings, dicts, custom objects, etc.)

##### Basic Usage

Let's enhance our `NarcolepticSuperhero` to track mission statistics:

```python
from tfism import Machine


class NarcolepticSuperhero(object):
    states = ['asleep', 'hanging out', 'hungry', 'sweaty', 'saving the world']

    def __init__(self, name):
        self.name = name
        self.kittens_rescued = 0

        # Initialize the state machine with send_event=True to access event_data
        self.machine = Machine(
            model=self,
            states=NarcolepticSuperhero.states,
            initial='asleep',
            send_event=True,  # Required for accessing event_data.state
            auto_transitions=True
        )

        # Add transitions
        self.machine.add_transition('wake_up', 'asleep', 'hanging out')
        self.machine.add_transition('work_out', 'hanging out', 'hungry')
        self.machine.add_transition('eat', 'hungry', 'hanging out')
        self.machine.add_transition('distress_call', '*', 'saving the world')
        self.machine.add_transition('complete_mission', 'saving the world', 'sweaty')
        self.machine.add_transition('clean_up', 'sweaty', 'asleep')
        self.machine.add_transition('nap', '*', 'asleep')

    def on_enter_saving_the_world(self, event_data):
        """Store mission start time when entering saving_the_world state"""
        import time
        event_data.state.pocket = {
            'start_time': time.time(),
            'villains_defeated': 0,
            'kittens_saved': 0
        }

    def on_exit_saving_the_world(self, event_data):
        """Calculate mission duration in on_exit - pocket is still available!"""
        import time
        mission_data = event_data.state.pocket
        if mission_data:
            duration = time.time() - mission_data['start_time']
            print(f"Mission completed in {duration:.2f} seconds")
            # Pocket will be cleared automatically after this callback

    def on_enter_hanging_out(self, event_data):
        """Store relaxation activity"""
        event_data.state.pocket = {'activity': 'chilling', 'energy_level': 100}


# Usage
>>> batman = NarcolepticSuperhero("Batman")
>>> batman.wake_up()

# Check pocket of 'hanging out' state
>>> state = batman.machine.get_state('hanging out')
>>> state.pocket
{'activity': 'chilling', 'energy_level': 100}

# Go save the world
>>> batman.distress_call()
>>> mission_state = batman.machine.get_state('saving the world')
>>> mission_state.pocket['start_time']
1703123456.789

# Complete the mission (triggers on_exit)
>>> batman.complete_mission()
Mission completed in 12.34 seconds

# Pocket is now cleared
>>> batman.machine.get_state('saving the world').pocket
None
```

##### Pocket Lifecycle

The pocket follows a clear lifecycle tied to state transitions:

1. **Initial value**: When a state is created, `pocket` is `None`
2. **Setting values**: You set pocket values, typically in `on_enter` callbacks
3. **Accessing values**: You can read pocket anytime the state is active
4. **Automatic clearing**: Pocket is set to `None` when state exits (after `on_exit` callbacks)

This means:
- Pocket is **still available** in `on_exit` callbacks for cleanup/processing
- Pocket is **cleared automatically** - no manual cleanup needed
- Pocket is **None** when state is not active

##### With AsyncMachine

Pocket works seamlessly with async state machines:

```python
from tfism.extensions.asyncio import AsyncMachine
import asyncio


class AsyncHero:
    def __init__(self):
        self.machine = AsyncMachine(
            model=self,
            states=['idle', 'fighting', 'resting'],
            initial='idle',
            send_event=True,
            auto_transitions=True
        )

    async def on_enter_fighting(self, event_data):
        # Simulate async work and store result
        await asyncio.sleep(0.1)
        event_data.state.pocket = {
            'enemies_defeated': 5,
            'battle_duration': 10.5
        }

    async def on_exit_fighting(self, event_data):
        # Pocket is still available here
        result = event_data.state.pocket
        await asyncio.sleep(0.05)  # Simulate cleanup
        print(f"Battle summary: {result}")


async def main():
    hero = AsyncHero()
    await hero.to_fighting()
    # ... some time later ...
    await hero.to_resting()
    # Pocket cleared automatically


asyncio.run(main())
```

##### With Hierarchical State Machines

In nested state machines, each state has its own independent pocket:

```python
from tfism.extensions.nesting import HierarchicalMachine


class ComplexHero:
    def __init__(self):
        states = [
            'idle',
            {
                'name': 'active',
                'children': [
                    'patrolling',
                    {
                        'name': 'combat',
                        'children': ['melee', 'ranged']
                    }
                ]
            }
        ]

        self.machine = HierarchicalMachine(
            model=self,
            states=states,
            initial='idle',
            send_event=True,
            auto_transitions=True
        )

    def on_enter_active(self, event_data):
        event_data.state.pocket = {'mode': 'active', 'energy': 100}

    def on_enter_active_combat(self, event_data):
        event_data.state.pocket = {'enemies': 3, 'weapon_ready': True}

    def on_enter_active_combat_melee(self, event_data):
        event_data.state.pocket = {'damage': 50, 'hits': 0}


# Usage
>>> hero = ComplexHero()
>>> hero.to_active()

# Each level has its own pocket
>>> hero.machine.get_state('active').pocket
{'mode': 'active', 'energy': 100}

>>> hero.to_active_combat_melee()

# Parent states retain their pockets (they didn't exit)
>>> hero.machine.get_state('active').pocket
{'mode': 'active', 'energy': 100}

>>> hero.machine.get_state('active_combat').pocket
{'enemies': 3, 'weapon_ready': True}

>>> hero.machine.get_state('active_combat_melee').pocket
{'damage': 50, 'hits': 0}

# Transition to sibling state
>>> hero.to_active_patrol()

# Only melee state exited and cleared pocket
>>> hero.machine.get_state('active_combat_melee').pocket
None

# Parent states still have their pockets
>>> hero.machine.get_state('active').pocket
{'mode': 'active', 'energy': 100}
```

##### Best Practices

1. **Use `send_event=True`**: To access `event_data.state.pocket` in callbacks, initialize the machine with `send_event=True`

2. **Set pocket early**: Set pocket values in `on_enter` callbacks for consistency

3. **Use meaningful data structures**: Store dicts or custom objects to keep related data together

4. **Don't rely on pocket for critical state**: Pocket is temporary and cleared on exit, use model attributes for persistent state

5. **Access via `machine.get_state()`**: To read a state's pocket from outside callbacks, use `machine.get_state('state_name').pocket`

6. **Available in `on_exit`**: Pocket is still accessible in `on_exit` callbacks for final processing

##### When to Use Pocket

**Good use cases:**
- Temporary computation results during state activation
- Metrics specific to a state instance (e.g., time spent, items processed)
- Debugging information during state lifecycle
- Data that needs to be passed between callbacks in the same state

**Not suitable for:**
- Persistent model state (use model attributes instead)
- Data that needs to survive state transitions (pocket is cleared on exit)
- Cross-state communication (use model attributes or parameters instead)

#### <a name="checking-state"></a>Checking state

You can always check the current state of the model by either:

- inspecting the `.state` attribute, or
- calling `is_«state name»()`

And if you want to retrieve the actual `State` object for the current state, you can do that through the `Machine` instance's `get_state()` method.

```python
lump.state
>>> 'solid'
lump.is_gas()
>>> False
lump.is_solid()
>>> True
machine.get_state(lump.state).name
>>> 'solid'
```

If you'd like you can choose your own state attribute name by passing the `model_attribute` argument while initializing the `Machine`. This will also change the name of `is_«state name»()` to `is_«model_attribute»_«state name»()` though. Similarly, auto transitions will be named `to_«model_attribute»_«state name»()` instead of `to_«state name»()`. This is done to allow multiple machines to work on the same model with individual state attribute names.

```python
lump = Matter()
machine = Machine(lump, states=['solid', 'liquid', 'gas'],  model_attribute='matter_state', initial='solid')
lump.matter_state
>>> 'solid'
# with a custom 'model_attribute', states can also be checked like this:
lump.is_matter_state_solid()
>>> True
lump.to_matter_state_gas()
>>> True
```

#### <a name="enum-state"></a>Enumerations

So far we have seen how we can give state names and use these names to work with our state machine.
If you favour stricter typing and more IDE code completion (or you just can't type 'sesquipedalophobia' any longer because the word scares you) using [Enumerations](https://docs.python.org/3/library/enum.html) might be what you are looking for:

```python
import enum
from tfism import Machine


class States(enum.Enum):
    ERROR = 0
    RED = 1
    YELLOW = 2
    GREEN = 3


transitions = [['proceed', States.RED, States.YELLOW],
               ['proceed', States.YELLOW, States.GREEN],
               ['error', '*', States.ERROR]]

m = Machine(states = States, transitions = transitions, initial = States.RED)
assert m.is_RED()
assert m.state is States.RED
state = m.get_state(States.RED)  # get tfism.State object
print(state.name)  # >>> RED
m.proceed()
m.proceed()
assert m.is_GREEN()
m.error()
assert m.state is States.ERROR
```

You can mix enums and strings if you like (e.g. `[States.RED, 'ORANGE', States.YELLOW, States.GREEN]`) but note that internally, `transitions` will still handle states by name (`enum.Enum.name`).
Thus, it is not possible to have the states `'GREEN'` and `States.GREEN` at the same time.

### <a name="transitions"></a>Transitions

Some of the above examples already illustrate the use of transitions in passing, but here we'll explore them in more detail.

As with states, each transition is represented internally as its own object – an instance of class `Transition`. The quickest way to initialize a set of transitions is to pass a dictionary, or list of dictionaries, to the `Machine` initializer. We already saw this above:

```python
transitions = [
    { 'trigger': 'melt', 'source': 'solid', 'dest': 'liquid' },
    { 'trigger': 'evaporate', 'source': 'liquid', 'dest': 'gas' },
    { 'trigger': 'sublimate', 'source': 'solid', 'dest': 'gas' },
    { 'trigger': 'ionize', 'source': 'gas', 'dest': 'plasma' }
]
machine = Machine(model=Matter(), states=states, transitions=transitions)
```

Defining transitions in dictionaries has the benefit of clarity, but can be cumbersome. If you're after brevity, you might choose to define transitions using lists. Just make sure that the elements in each list are in the same order as the positional arguments in the `Transition` initialization (i.e., `trigger`, `source`, `destination`, etc.).

The following list-of-lists is functionally equivalent to the list-of-dictionaries above:

```python
transitions = [
    ['melt', 'solid', 'liquid'],
    ['evaporate', 'liquid', 'gas'],
    ['sublimate', 'solid', 'gas'],
    ['ionize', 'gas', 'plasma']
]
```

Alternatively, you can add transitions to a `Machine` after initialization:

```python
machine = Machine(model=lump, states=states, initial='solid')
machine.add_transition('melt', source='solid', dest='liquid')
```

#### <a name="triggers"></a>Triggering a transition

For a transition to be executed, some event needs to _trigger_ it. There are two ways to do this:

1. Using the automatically attached method in the base model:
    ```python
    >>> lump.melt()
    >>> lump.state
    'liquid'
    >>> lump.evaporate()
    >>> lump.state
    'gas'
    ```
    
    Note how you don't have to explicitly define these methods anywhere; the name of each transition is bound to the model passed to the `Machine` initializer (in this case, `lump`). This also means that your model **should not** already contain methods with the same name as event triggers since `transitions` will only attach convenience methods to your model if the spot is not already taken. If you want to modify that behaviour, have a look at the [FAQ](examples/Frequently%20asked%20questions.ipynb).
2. Using the `trigger` method, now attached to your model (if it hasn't been there before). This method lets you execute transitions by name in case dynamic triggering is required:
    ```python
    >>> lump.trigger('melt')
    >>> lump.state
    'liquid'
    >>> lump.trigger('evaporate')
    >>> lump.state
    'gas'
    ```

#### Triggering invalid transitions

By default, triggering an invalid transition will raise an exception:

```python
>>> lump.to_gas()
>>> # This won't work because only objects in a solid state can melt
>>> lump.melt()
transitions.core.MachineError: "Can't trigger event melt from state gas!"
```

This behavior is generally desirable, since it helps alert you to problems in your code. But in some cases, you might want to silently ignore invalid triggers. You can do this by setting `ignore_invalid_triggers=True` (either on a state-by-state basis, or globally for all states):

```python
>>> # Globally suppress invalid trigger exceptions
>>> m = Machine(lump, states, initial='solid', ignore_invalid_triggers=True)
>>> # ...or suppress for only one group of states
>>> states = ['new_state1', 'new_state2']
>>> m.add_states(states, ignore_invalid_triggers=True)
>>> # ...or even just for a single state. Here, exceptions will only be suppressed when the current state is A.
>>> states = [State('A', ignore_invalid_triggers=True), 'B', 'C']
>>> m = Machine(lump, states)
>>> # ...this can be inverted as well if just one state should raise an exception
>>> # since the machine's global value is not applied to a previously initialized state.
>>> states = ['A', 'B', State('C')] # the default value for 'ignore_invalid_triggers' is False
>>> m = Machine(lump, states, ignore_invalid_triggers=True)
```

If you need to know which transitions are valid from a certain state, you can use `get_triggers`:

```python
m.get_triggers('solid')
>>> ['melt', 'sublimate']
m.get_triggers('liquid')
>>> ['evaporate']
m.get_triggers('plasma')
>>> []
# you can also query several states at once
m.get_triggers('solid', 'liquid', 'gas', 'plasma')
>>> ['melt', 'evaporate', 'sublimate', 'ionize']
```

If you have followed this documentation from the beginning, you will notice that `get_triggers` actually returns more triggers than the explicitly defined ones shown above, such as `to_liquid` and so on.
These are called `auto-transitions` and will be introduced in the next section.

#### <a name="automatic-transitions-for-all-states"></a>Automatic transitions for all states

In addition to any transitions added explicitly, a `to_«state»()` method is created automatically whenever a state is added to a `Machine` instance. This method transitions to the target state no matter which state the machine is currently in:

```python
lump.to_liquid()
lump.state
>>> 'liquid'
lump.to_solid()
lump.state
>>> 'solid'
```

If you desire, you can disable this behavior by setting `auto_transitions=False` in the `Machine` initializer.

#### <a name="transitioning-from-multiple-states"></a>Transitioning from multiple states

A given trigger can be attached to multiple transitions, some of which can potentially begin or end in the same state. For example:

```python
machine.add_transition('transmogrify', ['solid', 'liquid', 'gas'], 'plasma')
machine.add_transition('transmogrify', 'plasma', 'solid')
# This next transition will never execute
machine.add_transition('transmogrify', 'plasma', 'gas')
```

In this case, calling `transmogrify()` will set the model's state to `'solid'` if it's currently `'plasma'`, and set it to `'plasma'` otherwise. (Note that only the _first_ matching transition will execute; thus, the transition defined in the last line above won't do anything.)

You can also make a trigger cause a transition from _all_ states to a particular destination by using the `'*'` wildcard:

```python
machine.add_transition('to_liquid', '*', 'liquid')
```

Note that wildcard transitions will only apply to states that exist at the time of the add_transition() call. Calling a wildcard-based transition when the model is in a state added after the transition was defined will elicit an invalid transition message, and will not transition to the target state.

#### <a name="reflexive-from-multiple-states"></a>Reflexive transitions from multiple states

A reflexive trigger (trigger that has the same state as source and destination) can easily be added specifying `=` as destination.
This is handy if the same reflexive trigger should be added to multiple states.
For example:

```python
machine.add_transition('touch', ['liquid', 'gas', 'plasma'], '=', after='change_shape')
```

This will add reflexive transitions for all three states with `touch()` as trigger and with `change_shape` executed after each trigger.

#### <a name="internal-transitions"></a>Internal transitions

In contrast to reflexive transitions, internal transitions will never actually leave the state.
This means that transition-related callbacks such as `before` or `after` will be processed while state-related callbacks `exit` or `enter` will not.
To define a transition to be internal, set the destination to `None`.

```python
machine.add_transition('internal', ['liquid', 'gas'], None, after='change_shape')
```

#### <a name="ordered-transitions"></a> Ordered transitions

A common desire is for state transitions to follow a strict linear sequence. For instance, given states `['A', 'B', 'C']`, you might want valid transitions for `A` → `B`, `B` → `C`, and `C` → `A` (but no other pairs).

To facilitate this behavior, Transitions provides an `add_ordered_transitions()` method in the `Machine` class:

```python
states = ['A', 'B', 'C']
 # See the "alternative initialization" section for an explanation of the 1st argument to init
machine = Machine(states=states, initial='A')
machine.add_ordered_transitions()
machine.next_state()
print(machine.state)
>>> 'B'
# We can also define a different order of tfism
machine = Machine(states=states, initial='A')
machine.add_ordered_transitions(['A', 'C', 'B'])
machine.next_state()
print(machine.state)
>>> 'C'
# Conditions can be passed to 'add_ordered_transitions' as well
# If one condition is passed, it will be used for all tfism
machine = Machine(states=states, initial='A')
machine.add_ordered_transitions(conditions='check')
# If a list is passed, it must contain exactly as many elements as the
# machine contains states (A->B, ..., X->A)
machine = Machine(states=states, initial='A')
machine.add_ordered_transitions(conditions=['check_A2B', ..., 'check_X2A'])
# Conditions are always applied starting from the initial state
machine = Machine(states=states, initial='B')
machine.add_ordered_transitions(conditions=['check_B2C', ..., 'check_A2B'])
# With `loop=False`, the transition from the last state to the first state will be omitted (e.g. C->A)
# When you also pass conditions, you need to pass one condition less (len(states)-1)
machine = Machine(states=states, initial='A')
machine.add_ordered_transitions(loop=False)
machine.next_state()
machine.next_state()
machine.next_state() # tfism.core.MachineError: "Can't trigger event next_state from state C!"
```

#### <a name="queued-transitions"></a>Queued transitions

The default behaviour in Transitions is to process events instantly. This means events within an `on_enter` method will be processed _before_ callbacks bound to `after` are called.

```python
def go_to_C():
    global machine
    machine.to_C()

def after_advance():
    print("I am in state B now!")

def entering_C():
    print("I am in state C now!")

states = ['A', 'B', 'C']
machine = Machine(states=states, initial='A')

# we want a message when state transition to B has been completed
machine.add_transition('advance', 'A', 'B', after=after_advance)

# call transition from state B to state C
machine.on_enter_B(go_to_C)

# we also want a message when entering state C
machine.on_enter_C(entering_C)
machine.advance()
>>> 'I am in state C now!'
>>> 'I am in state B now!' # what?
```

The execution order of this example is

```
prepare -> before -> on_enter_B -> on_enter_C -> after.
```

If queued processing is enabled, a transition will be finished before the next transition is triggered:

```python
machine = Machine(states=states, queued=True, initial='A')
...
machine.advance()
>>> 'I am in state B now!'
>>> 'I am in state C now!' # That's better!
```

This results in

```
prepare -> before -> on_enter_B -> queue(to_C) -> after  -> on_enter_C.
```

**Important note:** when processing events in a queue, the trigger call will _alwa