python有限状态机很容易实现。
python-statemachine的Python项目详细描述
python finite-state machines很简单。
- 自由软件:麻省理工学院许可证
- 文档:https://python-statemachine.readthedocs.io。
开始
要安装python状态机,请在终端中运行此命令:
$ pip install python-statemachine
定义状态机:
fromstatemachineimportStateMachine,StateclassTrafficLightMachine(StateMachine):green=State('Green',initial=True)yellow=State('Yellow')red=State('Red')slowdown=green.to(yellow)stop=yellow.to(red)go=red.to(green)
现在您可以创建一个实例:
>>> traffic_light = TrafficLightMachine()
并检查当前状态:
>>> traffic_light.current_state State('Green', identifier='green', value='green', initial=True) >>> traffic_light.current_state == TrafficLightMachine.green == traffic_light.green True
对于每个状态,都有一个以is_<state.identifier>形式创建的数据属性 如果当前状态与查询匹配,则返回True:
>>> traffic_light.is_green True >>> traffic_light.is_yellow False >>> traffic_light.is_red False
元数据查询:
>>> [s.identifier for s in m.states] ['green', 'red', 'yellow'] >>> [t.identifier for t in m.transitions] ['go', 'slowdown', 'stop']
调用转换:
>>> traffic_light.slowdown()
并检查当前状态:
>>> traffic_light.current_state State('Yellow', identifier='yellow', value='yellow', initial=False) >>> traffic_light.is_yellow True
不能从无效状态运行转换:
>>> traffic_light.is_yellow True >>> traffic_light.slowdown() Traceback (most recent call last): ... LookupError: Can't slowdown when in Yellow.
您还可以通过另一种方式触发事件,调用run(<transition.identificer>)方法:
>>> traffic_light.is_yellow True >>> traffic_light.run('stop') >>> traffic_light.is_red True
状态机可以用初始值实例化:
>>> machine = TrafficLightMachine(start_value='red') >>> traffic_light.is_red True
型号
如果需要在另一个对象上保持当前状态,或者正在使用 状态机要控制另一个对象的流,可以传递此对象 到StateMachine构造函数:
>>> class MyModel(object): ... def __init__(self, state): ... self.state = state ... >>> obj = MyModel(state='red') >>> traffic_light = TrafficLightMachine(obj) >>> traffic_light.is_red True >>> obj.state 'red' >>> obj.state = 'green' >>> traffic_light.is_green True >>> traffic_light.slowdown() >>> obj.state 'yellow' >>> traffic_light.is_yellow True
回拨
运行事件时回调:
fromstatemachineimportStateMachine,StateclassTrafficLightMachine(StateMachine):"A traffic light machine"green=State('Green',initial=True)yellow=State('Yellow')red=State('Red')slowdown=green.to(yellow)stop=yellow.to(red)go=red.to(green)defon_slowdown(self):print('Calma, lá!')defon_stop(self):print('Parou.')defon_go(self):print('Valendo!')
>>> stm = TrafficLightMachine() >>> stm.slowdown() Calma, lá! >>> stm.stop() Parou. >>> stm.go() Valendo!<>或进入/退出状态:
fromstatemachineimportStateMachine,StateclassTrafficLightMachine(StateMachine):"A traffic light machine"green=State('Green',initial=True)yellow=State('Yellow')red=State('Red')cycle=green.to(yellow)|yellow.to(red)|red.to(green)defon_enter_green(self):print('Valendo!')defon_enter_yellow(self):print('Calma, lá!')defon_enter_red(self):print('Parou.')
>>> stm = TrafficLightMachine() >>> stm.cycle() Calma, lá! >>> stm.cycle() Parou. >>> stm.cycle() Valendo!
< H3>混合蛋白< EH3><>你的模型可以从自定义MIXIN继承到自动实例化状态机。
classCampaignMachineWithKeys(StateMachine):"A workflow machine"draft=State('Draft',initial=True,value=1)producing=State('Being produced',value=2)closed=State('Closed',value=3)add_job=draft.to.itself()|producing.to.itself()produce=draft.to(producing)deliver=producing.to(closed)classMyModel(MachineMixin):state_machine_name='CampaignMachine'def__init__(self,**kwargs):fork,vinkwargs.items():setattr(self,k,v)super(MyModel,self).__init__()def__repr__(self):return"{}({!r})".format(type(self).__name__,self.__dict__)model=MyModel(state='draft')assertisinstance(model.statemachine,campaign_machine)assertmodel.state=='draft'assertmodel.statemachine.current_state==model.statemachine.draft
历史记录
0.7.1(2019-01-18)
- 修复django1.7+上注册表加载statemachine模块的django集成。
0.7.0(2018-04-01)
- 新事件回调:
OnEnthull&lt;
0.6.2(2017-08-25)
- 修复自述文件。
0.6.1(2017-08-25)
- 修复部署问题。
0.6.0(2017-08-25)
- 在django项目下自动发现statemachine 他们要求使用MIXIN /注册表功能。
0.5.1(2017-07-24)
- 修复CombinedTransition._can_run上的错误,如果超过 两个过渡结合在一起。
0.5.0(2017-07-13)
- 自定义例外。
- 不允许on_execute回调的重复定义。
- 修复用额外的selfparam调用StateMachine.on_<transition.identifier>的错误。
0.4.2(2017-07-10)
- Python3.6支持。
- 放弃对Python3.3的官方支持。
- 转换可以用作执行回调定义时的装饰符。
- 转换可以指向多个目标状态。
0.3.0(2017-03-22)
- 自述入门部分。
- 无模型状态机的测试。
0.2.0(2017-03-22)
- State可以保存一个将作为状态值分配给模型的值。
- travis-ci集成。
- RTD集成。
0.1.0(2017-03-21)
- pypi上的第一个版本。