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 =

编辑推荐精选

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

AI办公办公工具AI工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图热门
讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

热门AI开发模型训练AI工具讯飞星火大模型智能问答内容创作多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

Trae

Trae

字节跳动发布的AI编程神器IDE

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

AI工具TraeAI IDE协作生产力转型热门
咔片PPT

咔片PPT

AI助力,做PPT更简单!

咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

热门AI辅助写作AI工具讯飞绘文内容运营AI创作个性化文章多平台分发AI助手
材料星

材料星

专业的AI公文写作平台,公文写作神器

AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

openai-agents-python

openai-agents-python

OpenAI Agents SDK,助力开发者便捷使用 OpenAI 相关功能。

openai-agents-python 是 OpenAI 推出的一款强大 Python SDK,它为开发者提供了与 OpenAI 模型交互的高效工具,支持工具调用、结果处理、追踪等功能,涵盖多种应用场景,如研究助手、财务研究等,能显著提升开发效率,让开发者更轻松地利用 OpenAI 的技术优势。

Hunyuan3D-2

Hunyuan3D-2

高分辨率纹理 3D 资产生成

Hunyuan3D-2 是腾讯开发的用于 3D 资产生成的强大工具,支持从文本描述、单张图片或多视角图片生成 3D 模型,具备快速形状生成能力,可生成带纹理的高质量 3D 模型,适用于多个领域,为 3D 创作提供了高效解决方案。

3FS

3FS

一个具备存储、管理和客户端操作等多种功能的分布式文件系统相关项目。

3FS 是一个功能强大的分布式文件系统项目,涵盖了存储引擎、元数据管理、客户端工具等多个模块。它支持多种文件操作,如创建文件和目录、设置布局等,同时具备高效的事件循环、节点选择和协程池管理等特性。适用于需要大规模数据存储和管理的场景,能够提高系统的性能和可靠性,是分布式存储领域的优质解决方案。

下拉加载更多