transitions

transitions

Python状态机库 轻量级实现与丰富扩展

transitions是一个轻量级的Python状态机库,支持Python 2.7+和3.0+版本。该库提供分层状态机、图表生成和多线程支持等扩展功能,方便用户定义状态、转换和回调。transitions设计简洁,适用于各种复杂的状态管理场景,使状态机的构建和管理变得简单高效。作为处理状态逻辑的工具,transitions在保持轻量级的同时提供了强大的功能。

状态机Pythontransitions库状态转换回调函数Github开源项目

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

Version Build Status Coverage Status PyPi Copr GitHub commits License Binder

<!-- [![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. 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

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:

from transitions 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 transitions. 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 transitions= 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...

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

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.

# The states states=['solid', 'liquid', 'gas', 'plasma'] # And some transitions between states. We're lazy, so we'll leave out # the inverse phase transitions (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 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:

# import Machine and State class from transitions 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 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.

# 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:

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.

from transitions import Machine, State states =

编辑推荐精选

扣子-AI办公

扣子-AI办公

职场AI,就用扣子

AI办公助手,复杂任务高效处理。办公效率低?扣子空间AI助手支持播客生成、PPT制作、网页开发及报告写作,覆盖科研、商业、舆情等领域的专家Agent 7x24小时响应,生活工作无缝切换,提升50%效率!

堆友

堆友

多风格AI绘画神器

堆友平台由阿里巴巴设计团队创建,作为一款AI驱动的设计工具,专为设计师提供一站式增长服务。功能覆盖海量3D素材、AI绘画、实时渲染以及专业抠图,显著提升设计品质和效率。平台不仅提供工具,还是一个促进创意交流和个人发展的空间,界面友好,适合所有级别的设计师和创意工作者。

图像生成AI工具AI反应堆AI工具箱AI绘画GOAI艺术字堆友相机AI图像热门
码上飞

码上飞

零代码AI应用开发平台

零代码AI应用开发平台,用户只需一句话简单描述需求,AI能自动生成小程序、APP或H5网页应用,无需编写代码。

Vora

Vora

免费创建高清无水印Sora视频

Vora是一个免费创建高清无水印Sora视频的AI工具

Refly.AI

Refly.AI

最适合小白的AI自动化工作流平台

无需编码,轻松生成可复用、可变现的AI自动化工作流

酷表ChatExcel

酷表ChatExcel

大模型驱动的Excel数据处理工具

基于大模型交互的表格处理系统,允许用户通过对话方式完成数据整理和可视化分析。系统采用机器学习算法解析用户指令,自动执行排序、公式计算和数据透视等操作,支持多种文件格式导入导出。数据处理响应速度保持在0.8秒以内,支持超过100万行数据的即时分析。

AI工具酷表ChatExcelAI智能客服AI营销产品使用教程
TRAE编程

TRAE编程

AI辅助编程,代码自动修复

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
AIWritePaper论文写作

AIWritePaper论文写作

AI论文写作指导平台

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

AI辅助写作AI工具AI论文工具论文写作智能生成大纲数据安全AI助手热门
博思AIPPT

博思AIPPT

AI一键生成PPT,就用博思AIPPT!

博思AIPPT,新一代的AI生成PPT平台,支持智能生成PPT、AI美化PPT、文本&链接生成PPT、导入Word/PDF/Markdown文档生成PPT等,内置海量精美PPT模板,涵盖商务、教育、科技等不同风格,同时针对每个页面提供多种版式,一键自适应切换,完美适配各种办公场景。

AI办公办公工具AI工具博思AIPPTAI生成PPT智能排版海量精品模板AI创作热门
潮际好麦

潮际好麦

AI赋能电商视觉革命,一站式智能商拍平台

潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图效率,让品牌能够快速上架。

下拉加载更多