简单有限状态机
pystatemachine的Python项目详细描述
pystatemachine
pystatemachine是一个通用的、但易于使用的有限状态机 用python编写的库。它提供函数来转换任何python 对象转换为有限状态自动机,该自动机从State更改为 另一个是由触发event启动的。
用法
有限状态机由其状态列表定义,并且 每次转换的触发条件。pystatemachine提供 eventdecorator对于类的绑定方法,aStateclass to 定义有限状态机的状态,以及 acts_as_state_machinedecorator,用于转换任何python(new-or 旧风格)类到一个有限状态机。默认情况下,任何 event-修饰的方法可能会引发错误。可选地,a transition_failure_handlerdecorator将任何类方法转换为 当event-修饰方法时调用的失败处理程序 引发错误。
示例
接下来,对旋转栅门进行建模。
An example of a very simple mechanism that can be modeled by a state machine is a turnstile. A turnstile is a gate with three rotating arms at waist height, one across the entryway. Initially the arms are locked, barring the entry, preventing customers from passing through. Depositing a coin or token in a slot on the turnstile unlocks the arms, allowing a single customer to push through. After the customer passes through, the arms are locked again until another coin is inserted. - from [Wikipedia] (http://en.wikipedia.org/wiki/Finite-state_machine#Example:_a_turnstile)
@acts_as_state_machineclassTurnstile(object):locked=State('locked',initial=True)unlocked=State('unlocked')@event(from_states=(locked,unlocked),to_state=unlocked)defcoin(self):assertrandom.random()>.5,'failing for demonstration purposes, only ..'print('*blingbling* .. unlocked!')@event(from_states=(locked,unlocked),to_state=locked)defpush(self):print('*push* .. locked!')@transition_failure_handler(calling_sequence=2)defturnstile_malfunction(self,method,from_state,to_state,error):print('state transition from {0.name} to {1.name} failed. Reason: {2}'.format(from_state,to_state,error))@transition_failure_handler(calling_sequence=1)defbefore_turnstile_malfunction(self,method,from_state,to_state,error):print('before state transition failure handler ..')importrandomturnstile=Turnstile()for_inrange(10):handler=random.choice([turnstile.coin,turnstile.push])handler()
更改日志
1.2
- 事件修饰函数中的异常现在在没有 已注册转换失败处理程序
1.1
- 添加了一个decorator,用于将类的方法注册为异常 “事件”修饰方法失败时的处理程序。多种方法可以 注册为转换失败处理程序:它们在 由可选的“calling_sequence”关键字给出的顺序
1.0
- 首次公开发行
许可证
pystatemachine在MIT License下可用。