百科.dev
全部条目AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
T

transitions

> 编程语言
开源

一个在 Python 中实现的轻量级、面向对象的有限状态机,具有许多扩展功能

6.6K stars0 点赞0 次浏览
访问官网GitHub

工具介绍

一个在 Python 中实现的轻量级、面向对象的有限状态机,具有许多扩展功能

transitions

A lightweight, object-oriented state machine implementation in Python with many extensions. Compatible with Python 2.7+ and 3.0+.

Installation

pip install transitions

... or clone the repo from GitHub and then:

python setup.py install

Table of Contents

  • Quickstart
  • Non-Quickstart
    • Some key concepts
    • Basic initialization
    • States
      • Callbacks
      • Checking state
      • Enumerations
    • Transitions
      • Triggering a transition
      • Automatic transitions
      • Transitioning from multiple states
      • Reflexive transitions from multiple states
      • Internal transitions
      • Ordered transitions
      • Queued transitions
      • Conditional transitions
      • Check transitions
      • Callbacks
    • Callable resolution
    • Callback execution order
    • Passing data
    • Alternative initialization patterns
    • Logging
    • (Re-)Storing machine instances
    • Typing support
    • Extensions
      • Hierarchical State Machine
      • Diagrams
      • Threading
      • Async
      • State features
      • Django
    • Bug reports etc.

Quickstart

They say a good example is worth 100 pages of API documentation, a million directives, or a thousand words.

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

…

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

…

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

Have a look at the 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 transitions, 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:

class Matter(object):
    pass

lump = Matter()

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

from transitions 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:


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.

…

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

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:

…

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 in case you require some other behaviour.

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.

…

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:

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.

…

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.

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.

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

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 might be what you are looking for:

…

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.

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:

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:

transitions = [
    ['melt', 'solid', 'liquid'],
    ['evaporate', 'liquid', 'gas'],
    ['sublimate',

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Pythonhierarchical-state-machinenested-statespythonstate-diagram

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言