METADATA 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581
  1. Metadata-Version: 2.1
  2. Name: transitions
  3. Version: 0.8.1
  4. Summary: A lightweight, object-oriented Python state machine implementation with many extensions.
  5. Home-page: http://github.com/pytransitions/transitions
  6. Author: Tal Yarkoni
  7. Author-email: tyarkoni@gmail.com
  8. Maintainer: Alexander Neumann
  9. Maintainer-email: aleneum@gmail.com
  10. License: MIT
  11. Download-URL: https://github.com/pytransitions/transitions/archive/0.8.1.tar.gz
  12. Platform: UNKNOWN
  13. Classifier: License :: OSI Approved :: MIT License
  14. Classifier: Programming Language :: Python :: 2
  15. Classifier: Programming Language :: Python :: 2.7
  16. Classifier: Programming Language :: Python :: 3
  17. Classifier: Programming Language :: Python :: 3.3
  18. Classifier: Programming Language :: Python :: 3.4
  19. Classifier: Programming Language :: Python :: 3.5
  20. Classifier: Programming Language :: Python :: 3.6
  21. Classifier: Programming Language :: Python :: 3.7
  22. Classifier: Programming Language :: Python :: 3.8
  23. Description-Content-Type: text/markdown
  24. Requires-Dist: six
  25. Provides-Extra: diagrams
  26. Requires-Dist: pygraphviz ; extra == 'diagrams'
  27. Provides-Extra: test
  28. Requires-Dist: pytest ; extra == 'test'
  29. ## Quickstart
  30. They say [a good example is worth](https://www.google.com/webhp?ie=UTF-8#q=%22a+good+example+is+worth%22&start=20) 100 pages of API documentation, a million directives, or a thousand words.
  31. Well, "they" probably lie... but here's an example anyway:
  32. ```python
  33. from transitions import Machine
  34. import random
  35. class NarcolepticSuperhero(object):
  36. # Define some states. Most of the time, narcoleptic superheroes are just like
  37. # everyone else. Except for...
  38. states = ['asleep', 'hanging out', 'hungry', 'sweaty', 'saving the world']
  39. def __init__(self, name):
  40. # No anonymous superheroes on my watch! Every narcoleptic superhero gets
  41. # a name. Any name at all. SleepyMan. SlumberGirl. You get the idea.
  42. self.name = name
  43. # What have we accomplished today?
  44. self.kittens_rescued = 0
  45. # Initialize the state machine
  46. self.machine = Machine(model=self, states=NarcolepticSuperhero.states, initial='asleep')
  47. # Add some transitions. We could also define these using a static list of
  48. # dictionaries, as we did with states above, and then pass the list to
  49. # the Machine initializer as the transitions= argument.
  50. # At some point, every superhero must rise and shine.
  51. self.machine.add_transition(trigger='wake_up', source='asleep', dest='hanging out')
  52. # Superheroes need to keep in shape.
  53. self.machine.add_transition('work_out', 'hanging out', 'hungry')
  54. # Those calories won't replenish themselves!
  55. self.machine.add_transition('eat', 'hungry', 'hanging out')
  56. # Superheroes are always on call. ALWAYS. But they're not always
  57. # dressed in work-appropriate clothing.
  58. self.machine.add_transition('distress_call', '*', 'saving the world',
  59. before='change_into_super_secret_costume')
  60. # When they get off work, they're all sweaty and disgusting. But before
  61. # they do anything else, they have to meticulously log their latest
  62. # escapades. Because the legal department says so.
  63. self.machine.add_transition('complete_mission', 'saving the world', 'sweaty',
  64. after='update_journal')
  65. # Sweat is a disorder that can be remedied with water.
  66. # Unless you've had a particularly long day, in which case... bed time!
  67. self.machine.add_transition('clean_up', 'sweaty', 'asleep', conditions=['is_exhausted'])
  68. self.machine.add_transition('clean_up', 'sweaty', 'hanging out')
  69. # Our NarcolepticSuperhero can fall asleep at pretty much any time.
  70. self.machine.add_transition('nap', '*', 'asleep')
  71. def update_journal(self):
  72. """ Dear Diary, today I saved Mr. Whiskers. Again. """
  73. self.kittens_rescued += 1
  74. @property
  75. def is_exhausted(self):
  76. """ Basically a coin toss. """
  77. return random.random() < 0.5
  78. def change_into_super_secret_costume(self):
  79. print("Beauty, eh?")
  80. ```
  81. There, now you've baked a state machine into `NarcolepticSuperhero`. Let's take him/her/it out for a spin...
  82. ```python
  83. >>> batman = NarcolepticSuperhero("Batman")
  84. >>> batman.state
  85. 'asleep'
  86. >>> batman.wake_up()
  87. >>> batman.state
  88. 'hanging out'
  89. >>> batman.nap()
  90. >>> batman.state
  91. 'asleep'
  92. >>> batman.clean_up()
  93. MachineError: "Can't trigger event clean_up from state asleep!"
  94. >>> batman.wake_up()
  95. >>> batman.work_out()
  96. >>> batman.state
  97. 'hungry'
  98. # Batman still hasn't done anything useful...
  99. >>> batman.kittens_rescued
  100. 0
  101. # We now take you live to the scene of a horrific kitten entreement...
  102. >>> batman.distress_call()
  103. 'Beauty, eh?'
  104. >>> batman.state
  105. 'saving the world'
  106. # Back to the crib.
  107. >>> batman.complete_mission()
  108. >>> batman.state
  109. 'sweaty'
  110. >>> batman.clean_up()
  111. >>> batman.state
  112. 'asleep' # Too tired to shower!
  113. # Another productive day, Alfred.
  114. >>> batman.kittens_rescued
  115. 1
  116. ```
  117. ## The non-quickstart
  118. ### Basic initialization
  119. 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:
  120. ```python
  121. class Matter(object):
  122. pass
  123. lump = Matter()
  124. ```
  125. You can initialize a (_minimal_) working state machine bound to `lump` like this:
  126. ```python
  127. from transitions import Machine
  128. machine = Machine(model=lump, states=['solid', 'liquid', 'gas', 'plasma'], initial='solid')
  129. # Lump now has state!
  130. lump.state
  131. >>> 'solid'
  132. ```
  133. I say "minimal", 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!
  134. Let's try again.
  135. ```python
  136. # The states
  137. states=['solid', 'liquid', 'gas', 'plasma']
  138. # And some transitions between states. We're lazy, so we'll leave out
  139. # the inverse phase transitions (freezing, condensation, etc.).
  140. transitions = [
  141. { 'trigger': 'melt', 'source': 'solid', 'dest': 'liquid' },
  142. { 'trigger': 'evaporate', 'source': 'liquid', 'dest': 'gas' },
  143. { 'trigger': 'sublimate', 'source': 'solid', 'dest': 'gas' },
  144. { 'trigger': 'ionize', 'source': 'gas', 'dest': 'plasma' }
  145. ]
  146. # Initialize
  147. machine = Machine(lump, states=states, transitions=transitions, initial='liquid')
  148. # Now lump maintains state...
  149. lump.state
  150. >>> 'liquid'
  151. # And that state can change...
  152. lump.evaporate()
  153. lump.state
  154. >>> 'gas'
  155. lump.trigger('ionize')
  156. lump.state
  157. >>> 'plasma'
  158. ```
  159. Notice the shiny new methods attached to the `Matter` instance (`evaporate()`, `ionize()`, etc.). Each method triggers the corresponding transition. You don't have to explicitly define these methods anywhere; the name of each transition is bound to the model passed to the `Machine` initializer (in this case, `lump`).
  160. Additionally, there is a method called `trigger` now attached to your model.
  161. This method lets you execute transitions by name in case dynamic triggering is required.
  162. ### <a name="states"></a>States
  163. 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.
  164. You can initialize and modify States in a number of ways. Specifically, you can:
  165. - pass a string to the `Machine` initializer giving the name(s) of the state(s), or
  166. - directly initialize each new `State` object, or
  167. - pass a dictionary with initialization arguments
  168. The following snippets illustrate several ways to achieve the same goal:
  169. ```python
  170. # import Machine and State class
  171. from transitions import State
  172. # Create a list of 3 states to pass to the Machine
  173. # initializer. We can mix types; in this case, we
  174. # pass one State, one string, and one dict.
  175. states = [
  176. State(name='solid'),
  177. 'liquid',
  178. { 'name': 'gas'}
  179. ]
  180. machine = Machine(lump, states)
  181. # This alternative example illustrates more explicit
  182. # addition of states and state callbacks, but the net
  183. # result is identical to the above.
  184. machine = Machine(lump)
  185. solid = State('solid')
  186. liquid = State('liquid')
  187. gas = State('gas')
  188. machine.add_states([solid, liquid, gas])
  189. ```
  190. 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](#state-features) in case you require some other behaviour.
  191. #### <a name="state-callbacks"></a>Callbacks
  192. 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, or add them later.
  193. 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.
  194. ```python
  195. # Our old Matter class, now with a couple of new methods we
  196. # can trigger when entering or exit states.
  197. class Matter(object):
  198. def say_hello(self): print("hello, new state!")
  199. def say_goodbye(self): print("goodbye, old state!")
  200. lump = Matter()
  201. # Same states as above, but now we give StateA an exit callback
  202. states = [
  203. State(name='solid', on_exit=['say_goodbye']),
  204. 'liquid',
  205. { 'name': 'gas' }
  206. ]
  207. machine = Machine(lump, states=states)
  208. machine.add_transition('sublimate', 'solid', 'gas')
  209. # Callbacks can also be added after initialization using
  210. # the dynamically added on_enter_ and on_exit_ methods.
  211. # Note that the initial call to add the callback is made
  212. # on the Machine and not on the model.
  213. machine.on_enter_gas('say_hello')
  214. # Test out the callbacks...
  215. machine.set_state('solid')
  216. lump.sublimate()
  217. >>> 'goodbye, old state!'
  218. >>> 'hello, new state!'
  219. ```
  220. 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.)
  221. 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:
  222. ```python
  223. class Matter(object):
  224. def say_hello(self): print("hello, new state!")
  225. def say_goodbye(self): print("goodbye, old state!")
  226. def on_enter_A(self): print("We've just entered state A!")
  227. lump = Matter()
  228. machine = Machine(lump, states=['A', 'B', 'C'])
  229. ```
  230. Now, any time `lump` transitions to state `A`, the `on_enter_A()` method defined in the `Matter` class will fire.
  231. #### <a name="checking-state"></a>Checking state
  232. You can always check the current state of the model by either:
  233. - inspecting the `.state` attribute, or
  234. - calling `is_«state name»()`
  235. 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.
  236. ```python
  237. lump.state
  238. >>> 'solid'
  239. lump.is_gas()
  240. >>> False
  241. lump.is_solid()
  242. >>> True
  243. machine.get_state(lump.state).name
  244. >>> 'solid'
  245. ```
  246. If you'd like you track it using a different attribute, you could do that using the `model_attribute` argument while initializing the `Machine`.
  247. ```python
  248. lump = Matter()
  249. machine = Machine(lump, states=['solid', 'liquid', 'gas'], model_attribute='matter_state', initial='solid')
  250. lump.matter_state
  251. >>> 'solid'
  252. ```
  253. #### <a name="enum-state"></a>Enumerations
  254. So far we have seen how we can give state names and use these names to work with our state machine.
  255. 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](https://docs.python.org/3/library/enum.html) might be what you are looking for:
  256. ```python
  257. import enum # Python 2.7 users need to have 'enum34' installed
  258. from transitions import Machine
  259. class States(enum.Enum):
  260. ERROR = 0
  261. RED = 1
  262. YELLOW = 2
  263. GREEN = 3
  264. transitions = [['proceed', States.RED, States.YELLOW],
  265. ['proceed', States.YELLOW, States.GREEN],
  266. ['error', '*', States.ERROR]]
  267. m = Machine(states=States, transitions=transitions, initial=States.RED)
  268. assert m.is_RED()
  269. assert m.state is States.RED
  270. state = m.get_state(States.RED) # get transitions.State object
  271. print(state.name) # >>> RED
  272. m.proceed()
  273. m.proceed()
  274. assert m.is_GREEN()
  275. m.error()
  276. assert m.state is States.ERROR
  277. ```
  278. 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`).
  279. Thus, it is not possible to have the states `'GREEN'` and `States.GREEN` at the same time.
  280. ### <a name="transitions"></a>Transitions
  281. Some of the above examples already illustrate the use of transitions in passing, but here we'll explore them in more detail.
  282. 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:
  283. ```python
  284. transitions = [
  285. { 'trigger': 'melt', 'source': 'solid', 'dest': 'liquid' },
  286. { 'trigger': 'evaporate', 'source': 'liquid', 'dest': 'gas' },
  287. { 'trigger': 'sublimate', 'source': 'solid', 'dest': 'gas' },
  288. { 'trigger': 'ionize', 'source': 'gas', 'dest': 'plasma' }
  289. ]
  290. machine = Machine(model=Matter(), states=states, transitions=transitions)
  291. ```
  292. 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.).
  293. The following list-of-lists is functionally equivalent to the list-of-dictionaries above:
  294. ```python
  295. transitions = [
  296. ['melt', 'solid', 'liquid'],
  297. ['evaporate', 'liquid', 'gas'],
  298. ['sublimate', 'solid', 'gas'],
  299. ['ionize', 'gas', 'plasma']
  300. ]
  301. ```
  302. Alternatively, you can add transitions to a `Machine` after initialization:
  303. ```python
  304. machine = Machine(model=lump, states=states, initial='solid')
  305. machine.add_transition('melt', source='solid', dest='liquid')
  306. ```
  307. The `trigger` argument defines the name of the new triggering method that gets attached to the base model. When this method is called, it will try to execute the transition:
  308. ```python
  309. >>> lump.melt()
  310. >>> lump.state
  311. 'liquid'
  312. ```
  313. By default, calling an invalid trigger will raise an exception:
  314. ```python
  315. >>> lump.to_gas()
  316. >>> # This won't work because only objects in a solid state can melt
  317. >>> lump.melt()
  318. transitions.core.MachineError: "Can't trigger event melt from state gas!"
  319. ```
  320. This behavior is generally desirable, since it helps alert you to problems in your code. But in some cases, you might want to silently ignore invalid triggers. You can do this by setting `ignore_invalid_triggers=True` (either on a state-by-state basis, or globally for all states):
  321. ```python
  322. >>> # Globally suppress invalid trigger exceptions
  323. >>> m = Machine(lump, states, initial='solid', ignore_invalid_triggers=True)
  324. >>> # ...or suppress for only one group of states
  325. >>> states = ['new_state1', 'new_state2']
  326. >>> m.add_states(states, ignore_invalid_triggers=True)
  327. >>> # ...or even just for a single state. Here, exceptions will only be suppressed when the current state is A.
  328. >>> states = [State('A', ignore_invalid_triggers=True), 'B', 'C']
  329. >>> m = Machine(lump, states)
  330. >>> # ...this can be inverted as well if just one state should raise an exception
  331. >>> # since the machine's global value is not applied to a previously initialized state.
  332. >>> states = ['A', 'B', State('C')] # the default value for 'ignore_invalid_triggers' is False
  333. >>> m = Machine(lump, states, ignore_invalid_triggers=True)
  334. ```
  335. If you need to know which transitions are valid from a certain state, you can use `get_triggers`:
  336. ```
  337. m.get_triggers('solid')
  338. >>> ['melt', 'sublimate']
  339. m.get_triggers('liquid')
  340. >>> ['evaporate']
  341. m.get_triggers('plasma')
  342. >>> []
  343. # you can also query several states at once
  344. m.get_triggers('solid', 'liquid', 'gas', 'plasma')
  345. >>> ['melt', 'evaporate', 'sublimate', 'ionize']
  346. ```
  347. #### <a name="automatic-transitions-for-all-states"></a>Automatic transitions for all states
  348. In addition to any transitions added explicitly, a `to_«state»()` method is created automatically whenever a state is added to a `Machine` instance. This method transitions to the target state no matter which state the machine is currently in:
  349. ```python
  350. lump.to_liquid()
  351. lump.state
  352. >>> 'liquid'
  353. lump.to_solid()
  354. lump.state
  355. >>> 'solid'
  356. ```
  357. If you desire, you can disable this behavior by setting `auto_transitions=False` in the `Machine` initializer.
  358. #### <a name="transitioning-from-multiple-states"></a>Transitioning from multiple states
  359. A given trigger can be attached to multiple transitions, some of which can potentially begin or end in the same state. For example:
  360. ```python
  361. machine.add_transition('transmogrify', ['solid', 'liquid', 'gas'], 'plasma')
  362. machine.add_transition('transmogrify', 'plasma', 'solid')
  363. # This next transition will never execute
  364. machine.add_transition('transmogrify', 'plasma', 'gas')
  365. ```
  366. In this case, calling `transmogrify()` will set the model's state to `'solid'` if it's currently `'plasma'`, and set it to `'plasma'` otherwise. (Note that only the _first_ matching transition will execute; thus, the transition defined in the last line above won't do anything.)
  367. You can also make a trigger cause a transition from _all_ states to a particular destination by using the `'*'` wildcard:
  368. ```python
  369. machine.add_transition('to_liquid', '*', 'liquid')
  370. ```
  371. Note that wildcard transitions will only apply to states that exist at the time of the add_transition() call. Calling a wildcard-based transition when the model is in a state added after the transition was defined will elicit an invalid transition message, and will not transition to the target state.
  372. #### <a name="reflexive-from-multiple-states"></a>Reflexive transitions from multiple states
  373. A reflexive trigger (trigger that has the same state as source and destination) can easily be added specifying `=` as destination.
  374. This is handy if the same reflexive trigger should be added to multiple states.
  375. For example:
  376. ```python
  377. machine.add_transition('touch', ['liquid', 'gas', 'plasma'], '=', after='change_shape')
  378. ```
  379. This will add reflexive transitions for all three states with `touch()` as trigger and with `change_shape` executed after each trigger.
  380. #### <a name="internal-transitions"></a>Internal transitions
  381. In contrast to reflexive transitions, internal transitions will never actually leave the state.
  382. This means that transition-related callbacks such as `before` or `after` will be processed while state-related callbacks `exit` or `enter` will not.
  383. To define a transition to be internal, set the destination to `None`.
  384. ```python
  385. machine.add_transition('internal', ['liquid', 'gas'], None, after='change_shape')
  386. ```
  387. #### <a name="ordered-transitions"></a> Ordered transitions
  388. A common desire is for state transitions to follow a strict linear sequence. For instance, given states `['A', 'B', 'C']`, you might want valid transitions for `A` → `B`, `B` → `C`, and `C` → `A` (but no other pairs).
  389. To facilitate this behavior, Transitions provides an `add_ordered_transitions()` method in the `Machine` class:
  390. ```python
  391. states = ['A', 'B', 'C']
  392. # See the "alternative initialization" section for an explanation of the 1st argument to init
  393. machine = Machine(states=states, initial='A')
  394. machine.add_ordered_transitions()
  395. machine.next_state()
  396. print(machine.state)
  397. >>> 'B'
  398. # We can also define a different order of transitions
  399. machine = Machine(states=states, initial='A')
  400. machine.add_ordered_transitions(['A', 'C', 'B'])
  401. machine.next_state()
  402. print(machine.state)
  403. >>> 'C'
  404. # Conditions can be passed to 'add_ordered_transitions' as well
  405. # If one condition is passed, it will be used for all transitions
  406. machine = Machine(states=states, initial='A')
  407. machine.add_ordered_transitions(conditions='check')
  408. # If a list is passed, it must contain exactly as many elements as the
  409. # machine contains states (A->B, ..., X->A)
  410. machine = Machine(states=states, initial='A')
  411. machine.add_ordered_transitions(conditions=['check_A2B', ..., 'check_X2A'])
  412. ```
  413. #### <a name="queued-transitions"></a>Queued transitions
  414. The default behaviour in Transitions is to process events instantly. This means events within an `on_enter` method will be processed _before_ callbacks bound to `after` are called.
  415. ```python
  416. def go_to_C():
  417. global machine
  418. machine.to_C()
  419. def after_advance():
  420. print("I am in state B now!")
  421. def entering_C():
  422. print("I am in state C now!")
  423. states = ['A', 'B', 'C']
  424. machine = Machine(states=states, initial='A')
  425. # we want a message when state transition to B has been completed
  426. machine.add_transition('advance', 'A', 'B', after=after_advance)
  427. # call transition from state B to state C
  428. machine.on_enter_B(go_to_C)
  429. # we also want a message when entering state C
  430. machine.on_enter_C(entering_C)
  431. machine.advance()
  432. >>> 'I am in state C now!'
  433. >>> 'I am in state B now!' # what?
  434. ```
  435. The execution order of this example is
  436. ```
  437. prepare -> before -> on_enter_B -> on_enter_C -> after.
  438. ```
  439. If queued processing is enabled, a transition will be finished before the next transition is triggered:
  440. ```python
  441. machine = Machine(states=states, queued=True, initial='A')
  442. ...
  443. machine.advance()
  444. >>> 'I am in state B now!'
  445. >>> 'I am in state C now!' # That's better!
  446. ```
  447. This results in
  448. ```
  449. prepare -> before -> on_enter_B -> queue(to_C) -> after -> on_enter_C.
  450. ```
  451. **Important note:** when processing events in a queue, the trigger call will _always_ return `True`, since there is no way to determine at queuing time whether a transition involving queued calls will ultimately complete successfully. This is true even when only a single event is processed.
  452. ```python
  453. machine.add_transition('jump', 'A', 'C', conditions='will_fail')
  454. ...
  455. # queued=False
  456. machine.jump()
  457. >>> False
  458. # queued=True
  459. machine.jump()
  460. >>> True
  461. ```
  462. #### <a name="conditional-transitions"></a>Conditional transitions
  463. Sometimes you only want a particular transition to execute if a specific condition occurs. You can do this by passing a method, or list of methods, in the `conditions` argument:
  464. ```python
  465. # Our Matter class, now with a bunch of methods that return booleans.
  466. class Matter(object):
  467. def is_flammable(self): return False
  468. def is_really_hot(self): return True
  469. machine.add_transition('heat', 'solid', 'gas', conditions='is_flammable')
  470. machine.add_transition('heat', 'solid', 'liquid', conditions=['is_really_hot'])
  471. ```
  472. In the above example, calling `heat()` when the model is in state `'solid'` will transition to state `'gas'` if `is_flammable` returns `True`. Otherwise, it will transition to state `'liquid'` if `is_really_hot` returns `True`.
  473. For convenience, there's also an `'unless'` argument that behaves exactly like conditions, but inverted:
  474. ```python
  475. machine.add_transition('heat', 'solid', 'gas', unless=['is_flammable', 'is_really_hot'])
  476. ```
  477. In this case, the model would transition from solid to gas whenever `heat()` fires, provided that both `is_flammable()` and `is_really_hot()` return `False`.
  478. Note that condition-checking methods will passively receive optional arguments and/or data objects passed to triggering methods. For instance, the following call:
  479. ```python
  480. lump.heat(temp=74)
  481. # equivalent to lump.trigger('heat', temp=74)
  482. ```
  483. ... would pass the `temp=74` optional kwarg to the `is_flammable()` check (possibly wrapped in an `EventData` instance). For more on this, see the [Passing data](#passing-data) section below.
  484. #### <a name="transition-callbacks"></a>Callbacks
  485. You can attach callbacks to transitions as well as states. Every transition has `'before'` and `'after'` attributes that contain a list of methods to call before and after the transition executes:
  486. ```python
  487. class Matter(object):
  488. def make_hissing_noises(self): print("HISSSSSSSSSSSSSSSS")
  489. def disappear(self): print("where'd all the liquid go?")
  490. transitions = [
  491. { 'trigger': 'melt', 'source': 'solid', 'dest': 'liquid', 'before': 'make_hissing_noises'},
  492. { 'trigger': 'evaporate', 'source': 'liquid', 'dest': 'gas', 'after': 'disappear' }
  493. ]
  494. lump = Matter()
  495. machine = Machine(lump, states, transitions=transitions, initial='solid')
  496. lump.melt()
  497. >>> "HISSSSSSSSSSSSSSSS"
  498. lump.evaporate()
  499. >>> "where'd all the liquid go?"
  500. ```
  501. There is also a `'prepare'` callback that is executed as soon as a transition starts, before any `'conditions'` are checked or other callbacks are executed.
  502. ```python
  503. class Matter(object):
  504. heat = False
  505. attempts = 0
  506. def count_attempts(self): self.attempts += 1
  507. def heat_up(self): self.heat = random.random() < 0.25
  508. def stats(self): print('It took you %i attempts to melt the lump!' %self.attempts)
  509. @property
  510. def is_really_hot(self):
  511. return self.heat
  512. states=['solid', 'liquid', 'gas', 'plasma']
  513. transitions = [
  514. { 'trigger': 'melt', 'source': 'solid', 'dest': 'liquid', 'prepare': ['heat_up', 'count_attempts'], 'conditions': 'is_really_hot', 'after': 'stats'},
  515. ]
  516. lump = Matter()
  517. machine = Machine(lump, states, transitions=transitions, initial='solid')
  518. lump.melt()
  519. lump.melt()
  520. lump.melt()
  521. lump.melt()
  522. >>> "It took you 4 attempts to melt the lump!"
  523. ```
  524. Note that `prepare` will not be called unless the current state is a valid source for the named transition.
  525. Default actions meant to be executed before or after *every* transition can be passed to `Machine` during initialization with
  526. `before_state_change` and `after_state_change` respectively:
  527. ```python
  528. class Matter(object):
  529. def make_hissing_noises(self): print("HISSSSSSSSSSSSSSSS")
  530. def disappear(self): print("where'd all the liquid go?")
  531. states=['solid', 'liquid', 'gas', 'plasma']
  532. lump = Matter()
  533. m = Machine(lump, states, before_state_change='make_hissing_noises', after_state_change='disappear')
  534. lump.to_gas()
  535. >>> "HISSSSSSSSSSSSSSSS"
  536. >>> "where'd all the liquid go?"
  537. ```
  538. There are also two keywords for callbacks which should be executed *independently* a) of how many transitions are possible,
  539. b) if any transition succeeds and c) even if an error is raised during the execution of some other callback.
  540. Callbacks passed to `Machine` with `prepare_event` will be executed *once* before processing possible transitions
  541. (and their individual `prepare` callbacks) takes place.
  542. Callbacks of `finalize_event` will be executed regardless of the success of the processed transitions.
  543. Note that if an error occurred it will be attached to `event_data` as `error` and can be retrieved with `send_event=True`.
  544. ```python
  545. from transitions import Machine
  546. class Matter(object):
  547. def raise_error(self, event): raise ValueError("Oh no")
  548. def prepare(self, event): print("I am ready!")
  549. def finalize(self, event): print("Result: ", type(event.error), event.error)
  550. states=['solid', 'liquid', 'gas', 'plasma']
  551. lump = Matter()
  552. m = Machine(lump, states, prepare_event='prepare', before_state_change='raise_error',
  553. finalize_event='finalize', send_event=True)
  554. try:
  555. lump.to_gas()
  556. except ValueError:
  557. pass
  558. print(lump.state)
  559. >>> I am ready!
  560. >>> Result: <class 'ValueError'> Oh no
  561. >>> initial
  562. ```
  563. ### <a name="resolution"></a>Callable resolution
  564. As you have probably already realized, the standard way of passing callables to states, conditions and transitions is by name. When processing callbacks and conditions, `transitions` will use their name to retrieve the related callable from the model. If the method cannot be retrieved and it contains dots, `transitions` will treat the name as a path to a module function and try to import it. Alternatively, you can pass names of properties or attributes. They will be wrapped into functions but cannot receive event data for obvious reasons. You can also pass callables such as (bound) functions directly. As mentioned earlier, you can also pass lists/tuples of callables names to the callback parameters. Callbacks will be executed in the order they were added.
  565. ```python
  566. from transitions import Machine
  567. from mod import imported_func
  568. import random
  569. class Model(object):
  570. def a_callback(self):
  571. imported_func()
  572. @property
  573. def a_property(self):
  574. """ Basically a coin toss. """
  575. return random.random() < 0.5
  576. an_attribute = False
  577. model = Model()
  578. machine = Machine(model=model, states=['A'], initial='A')
  579. machine.add_transition('by_name', 'A', 'A', conditions='a_property', after='a_callback')
  580. machine.add_transition('by_reference', 'A', 'A', unless=['a_property', 'an_attribute'], after=model.a_callback)
  581. machine.add_transition('imported', 'A', 'A', after='mod.imported_func')
  582. model.by_name()
  583. model.by_reference()
  584. model.imported()
  585. ```
  586. The callable resolution is done in `Machine.resolve_callable`.
  587. This method can be overridden in case more complex callable resolution strategies are required.
  588. **Example**
  589. ```python
  590. class CustomMachine(Machine):
  591. @staticmethod
  592. def resolve_callable(func, event_data):
  593. # manipulate arguments here and return func, or super() if no manipulation is done.
  594. super(CustomMachine, CustomMachine).resolve_callable(func, event_data)
  595. ```
  596. ### <a name="execution-order"></a>Callback execution order
  597. In summary, callbacks on transitions are executed in the following order:
  598. | Callback | Current State | Comments |
  599. |--------------------------------|:-------------:|-------------------------------------------------------------|
  600. | `'machine.prepare_event'` | `source` | executed *once* before individual transitions are processed |
  601. | `'transition.prepare'` | `source` | executed as soon as the transition starts |
  602. | `'transition.conditions'` | `source` | conditions *may* fail and halt the transition |
  603. | `'transition.unless'` | `source` | conditions *may* fail and halt the transition |
  604. | `'machine.before_state_change'`| `source` | default callbacks declared on model |
  605. | `'transition.before'` | `source` | |
  606. | `'state.on_exit'` | `source` | callbacks declared on the source state |
  607. | `<STATE CHANGE>` | | |
  608. | `'state.on_enter'` | `destination` | callbacks declared on the destination state |
  609. | `'transition.after'` | `destination` | |
  610. | `'machine.after_state_change'` | `destination` | default callbacks declared on model |
  611. | `'machine.finalize_event'` | `source/destination` | callbacks will be executed even if no transition took place or an exception has been raised |
  612. If any callback raises an exception, the processing of callbacks is not continued. This means that when an error occurs before the transition (in `state.on_exit` or earlier), it is halted. In case there is a raise after the transition has been conducted (in `state.on_enter` or later), the state change persists and no rollback is happening. Callbacks specified in `machine.finalize_event` will always be executed unless the exception is raised by a finalizing callback itself.
  613. ### <a name="passing-data"></a>Passing data
  614. Sometimes you need to pass the callback functions registered at machine initialization some data that reflects the model's current state. Transitions allows you to do this in two different ways.
  615. First (the default), you can pass any positional or keyword arguments directly to the trigger methods (created when you call `add_transition()`):
  616. ```python
  617. class Matter(object):
  618. def __init__(self): self.set_environment()
  619. def set_environment(self, temp=0, pressure=101.325):
  620. self.temp = temp
  621. self.pressure = pressure
  622. def print_temperature(self): print("Current temperature is %d degrees celsius." % self.temp)
  623. def print_pressure(self): print("Current pressure is %.2f kPa." % self.pressure)
  624. lump = Matter()
  625. machine = Machine(lump, ['solid', 'liquid'], initial='solid')
  626. machine.add_transition('melt', 'solid', 'liquid', before='set_environment')
  627. lump.melt(45) # positional arg;
  628. # equivalent to lump.trigger('melt', 45)
  629. lump.print_temperature()
  630. >>> 'Current temperature is 45 degrees celsius.'
  631. machine.set_state('solid') # reset state so we can melt again
  632. lump.melt(pressure=300.23) # keyword args also work
  633. lump.print_pressure()
  634. >>> 'Current pressure is 300.23 kPa.'
  635. ```
  636. You can pass any number of arguments you like to the trigger.
  637. There is one important limitation to this approach: every callback function triggered by the state transition must be able to handle _all_ of the arguments. This may cause problems if the callbacks each expect somewhat different data.
  638. To get around this, Transitions supports an alternate method for sending data. If you set `send_event=True` at `Machine` initialization, all arguments to the triggers will be wrapped in an `EventData` instance and passed on to every callback. (The `EventData` object also maintains internal references to the source state, model, transition, machine, and trigger associated with the event, in case you need to access these for anything.)
  639. ```python
  640. class Matter(object):
  641. def __init__(self):
  642. self.temp = 0
  643. self.pressure = 101.325
  644. # Note that the sole argument is now the EventData instance.
  645. # This object stores positional arguments passed to the trigger method in the
  646. # .args property, and stores keywords arguments in the .kwargs dictionary.
  647. def set_environment(self, event):
  648. self.temp = event.kwargs.get('temp', 0)
  649. self.pressure = event.kwargs.get('pressure', 101.325)
  650. def print_pressure(self): print("Current pressure is %.2f kPa." % self.pressure)
  651. lump = Matter()
  652. machine = Machine(lump, ['solid', 'liquid'], send_event=True, initial='solid')
  653. machine.add_transition('melt', 'solid', 'liquid', before='set_environment')
  654. lump.melt(temp=45, pressure=1853.68) # keyword args
  655. lump.print_pressure()
  656. >>> 'Current pressure is 1853.68 kPa.'
  657. ```
  658. ### <a name="alternative-initialization-patterns"></a>Alternative initialization patterns
  659. In all of the examples so far, we've attached a new `Machine` instance to a separate model (`lump`, an instance of class `Matter`). While this separation keeps things tidy (because you don't have to monkey patch a whole bunch of new methods into the `Matter` class), it can also get annoying, since it requires you to keep track of which methods are called on the state machine, and which ones are called on the model that the state machine is bound to (e.g., `lump.on_enter_StateA()` vs. `machine.add_transition()`).
  660. Fortunately, Transitions is flexible, and supports two other initialization patterns.
  661. First, you can create a standalone state machine that doesn't require another model at all. Simply omit the model argument during initialization:
  662. ```python
  663. machine = Machine(states=states, transitions=transitions, initial='solid')
  664. machine.melt()
  665. machine.state
  666. >>> 'liquid'
  667. ```
  668. If you initialize the machine this way, you can then attach all triggering events (like `evaporate()`, `sublimate()`, etc.) and all callback functions directly to the `Machine` instance.
  669. This approach has the benefit of consolidating all of the state machine functionality in one place, but can feel a little bit unnatural if you think state logic should be contained within the model itself rather than in a separate controller.
  670. An alternative (potentially better) approach is to have the model inherit from the `Machine` class. Transitions is designed to support inheritance seamlessly. (just be sure to override class `Machine`'s `__init__` method!):
  671. ```python
  672. class Matter(Machine):
  673. def say_hello(self): print("hello, new state!")
  674. def say_goodbye(self): print("goodbye, old state!")
  675. def __init__(self):
  676. states = ['solid', 'liquid', 'gas']
  677. Machine.__init__(self, states=states, initial='solid')
  678. self.add_transition('melt', 'solid', 'liquid')
  679. lump = Matter()
  680. lump.state
  681. >>> 'solid'
  682. lump.melt()
  683. lump.state
  684. >>> 'liquid'
  685. ```
  686. Here you get to consolidate all state machine functionality into your existing model, which often feels more natural way than sticking all of the functionality we want in a separate standalone `Machine` instance.
  687. A machine can handle multiple models which can be passed as a list like `Machine(model=[model1, model2, ...])`.
  688. In cases where you want to add models *as well as* the machine instance itself, you can pass the string placeholder `'self'` during initialization like `Machine(model=['self', model1, ...])`.
  689. You can also create a standalone machine, and register models dynamically via `machine.add_model`.
  690. Remember to call `machine.remove_model` if machine is long-lasting and your models are temporary and should be garbage collected:
  691. ```python
  692. class Matter():
  693. pass
  694. lump1 = Matter()
  695. lump2 = Matter()
  696. machine = Machine(states=states, transitions=transitions, initial='solid', add_self=False)
  697. machine.add_model(lump1)
  698. machine.add_model(lump2, initial='liquid')
  699. lump1.state
  700. >>> 'solid'
  701. lump2.state
  702. >>> 'liquid'
  703. machine.remove_model([lump1, lump2])
  704. del lump1 # lump1 is garbage collected
  705. del lump2 # lump2 is garbage collected
  706. ```
  707. If you don't provide an initial state in the state machine constructor, you must provide one every time you add a model:
  708. ```python
  709. machine = Machine(states=states, transitions=transitions, add_self=False)
  710. machine.add_model(Matter())
  711. >>> "MachineError: No initial state configured for machine, must specify when adding model."
  712. machine.add_model(Matter(), initial='liquid')
  713. ```
  714. Models with multiple states could attach multiple machines using different `model_attribute` values:
  715. ```python
  716. lump = Matter()
  717. lump.state
  718. >>> 'solid'
  719. lump.shipping_state
  720. >>> 'delivered'
  721. matter_machine = Machine(lump, model_attribute='state', **kwargs)
  722. shipment_machine = Machine(lump, model_attribute='shipping_state', **kwargs)
  723. ```
  724. ### Logging
  725. Transitions includes very rudimentary logging capabilities. A number of events – namely, state changes, transition triggers, and conditional checks – are logged as INFO-level events using the standard Python `logging` module. This means you can easily configure logging to standard output in a script:
  726. ```python
  727. # Set up logging; The basic log level will be DEBUG
  728. import logging
  729. logging.basicConfig(level=logging.DEBUG)
  730. # Set transitions' log level to INFO; DEBUG messages will be omitted
  731. logging.getLogger('transitions').setLevel(logging.INFO)
  732. # Business as usual
  733. machine = Machine(states=states, transitions=transitions, initial='solid')
  734. ...
  735. ```
  736. ### <a name="restoring"></a>(Re-)Storing machine instances
  737. Machines are picklable and can be stored and loaded with `pickle`. For Python 3.3 and earlier `dill` is required.
  738. ```python
  739. import dill as pickle # only required for Python 3.3 and earlier
  740. m = Machine(states=['A', 'B', 'C'], initial='A')
  741. m.to_B()
  742. m.state
  743. >>> B
  744. # store the machine
  745. dump = pickle.dumps(m)
  746. # load the Machine instance again
  747. m2 = pickle.loads(dump)
  748. m2.state
  749. >>> B
  750. m2.states.keys()
  751. >>> ['A', 'B', 'C']
  752. ```
  753. ### <a name="extensions"></a> Extensions
  754. Even though the core of transitions is kept lightweight, there are a variety of MixIns to extend its functionality. Currently supported are:
  755. - **Diagrams** to visualize the current state of a machine
  756. - **Hierarchical State Machines** for nesting and reuse
  757. - **Threadsafe Locks** for parallel execution
  758. - **Async callbacks** for asynchronous execution
  759. - **Custom States** for extended state-related behaviour
  760. There are two mechanisms to retrieve a state machine instance with the desired features enabled.
  761. The first approach makes use of the convenience `factory` with the four parameters `graph`, `nested`, `locked` or `asyncio` set to `True` if the feature is required:
  762. ```python
  763. from transitions.extensions import MachineFactory
  764. # create a machine with mixins
  765. diagram_cls = MachineFactory.get_predefined(graph=True)
  766. nested_locked_cls = MachineFactory.get_predefined(nested=True, locked=True)
  767. async_machine_cls = MachineFactory.get_predefined(asyncio=True)
  768. # create instances from these classes
  769. # instances can be used like simple machines
  770. machine1 = diagram_cls(model, state, transitions)
  771. machine2 = nested_locked_cls(model, state, transitions)
  772. ```
  773. This approach targets experimental use since in this case the underlying classes do not have to be known.
  774. However, classes can also be directly imported from `transitions.extensions`. The naming scheme is as follows:
  775. | | Diagrams | Nested | Locked | Asyncio |
  776. | -----------------------------: | :------: | :----: | :----: | :---: |
  777. | Machine | ✘ | ✘ | ✘ | ✘ |
  778. | GraphMachine | ✓ | ✘ | ✘ | ✘ |
  779. | HierarchicalMachine | ✘ | ✓ | ✘ | ✘ |
  780. | LockedMachine | ✘ | ✘ | ✓ | ✘ |
  781. | HierarchicalGraphMachine | ✓ | ✓ | ✘ | ✘ |
  782. | LockedGraphMachine | ✓ | ✘ | ✓ | ✘ |
  783. | LockedHierarchicalMachine | ✘ | ✓ | ✓ | ✘ |
  784. | LockedHierarchicalGraphMachine | ✓ | ✓ | ✓ | ✘ |
  785. | AsyncMachine | ✘ | ✘ | ✘ | ✓ |
  786. | AsyncGraphMachine | ✓ | ✘ | ✘ | ✓ |
  787. | AsyncHierarchicalMachine | ✘ | ✓ | ✘ | ✓ |
  788. | AsyncHierarchicalGraphMachine | ✓ | ✓ | ✘ | ✓ |
  789. To use a feature-rich state machine, one could write:
  790. ```python
  791. from transitions.extensions import LockedHierarchicalGraphMachine as Machine
  792. machine = Machine(model, states, transitions)
  793. ```
  794. #### <a name="diagrams"></a> Diagrams
  795. Additional Keywords:
  796. * `title` (optional): Sets the title of the generated image.
  797. * `show_conditions` (default False): Shows conditions at transition edges
  798. * `show_auto_transitions` (default False): Shows auto transitions in graph
  799. * `show_state_attributes` (default False): Show callbacks (enter, exit), tags and timeouts in graph
  800. Transitions can generate basic state diagrams displaying all valid transitions between states. To use the graphing functionality, you'll need to have `graphviz` and/or `pygraphviz` installed:
  801. To generate graphs with the package `graphviz`, you need to install [Graphviz](https://graphviz.org/) manually or via a package manager.
  802. sudo apt-get install graphviz # Ubuntu and Debian
  803. brew install graphviz # MacOS
  804. conda install graphviz python-graphviz # (Ana)conda
  805. Now you can install the actual Python packages
  806. pip install graphviz pygraphviz # install graphviz and/or pygraphviz manually...
  807. pip install transitions[diagrams] # ... or install transitions with 'diagrams' extras which currently depends on pygraphviz
  808. Currently, `GraphMachine` will use `pygraphviz` when available and fall back to `graphviz` when `pygraphviz` cannot be
  809. found. This can be overridden by passing `use_pygraphviz=False` to the constructor. Note that this default might change
  810. in the future and `pygraphviz` support may be dropped.
  811. With `Model.get_graph()` you can get the current graph or the region of interest (roi) and draw it like this:
  812. ```python
  813. # import transitions
  814. from transitions.extensions import GraphMachine as Machine
  815. m = Model()
  816. # without further arguments pygraphviz will be used
  817. machine = Machine(model=m, ...)
  818. # when you want to use graphviz explicitely
  819. machine = Machine(model=m, use_pygraphviz=False, ...)
  820. # in cases where auto transitions should be visible
  821. machine = Machine(model=m, show_auto_transitions=True, ...)
  822. # draw the whole graph ...
  823. m.get_graph().draw('my_state_diagram.png', prog='dot')
  824. # ... or just the region of interest
  825. # (previous state, active state and all reachable states)
  826. roi = m.get_graph(show_roi=True).draw('my_state_diagram.png', prog='dot')
  827. ```
  828. This produces something like this:
  829. ![state diagram example](https://user-images.githubusercontent.com/205986/47524268-725c1280-d89a-11e8-812b-1d3b6e667b91.png)
  830. Also, have a look at our [example](./examples) IPython/Jupyter notebooks for a more detailed example.
  831. ### <a name="hsm"></a>Hierarchical State Machine (HSM)
  832. Transitions includes an extension module which allows to nest states.
  833. This allows to create contexts and to model cases where states are related to certain subtasks in the state machine.
  834. To create a nested state, either import `NestedState` from transitions or use a dictionary with the initialization arguments `name` and `children`.
  835. Optionally, `initial` can be used to define a sub state to transit to, when the nested state is entered.
  836. ```python
  837. from transitions.extensions import HierarchicalMachine as Machine
  838. states = ['standing', 'walking', {'name': 'caffeinated', 'children':['dithering', 'running']}]
  839. transitions = [
  840. ['walk', 'standing', 'walking'],
  841. ['stop', 'walking', 'standing'],
  842. ['drink', '*', 'caffeinated'],
  843. ['walk', ['caffeinated', 'caffeinated_dithering'], 'caffeinated_running'],
  844. ['relax', 'caffeinated', 'standing']
  845. ]
  846. machine = Machine(states=states, transitions=transitions, initial='standing', ignore_invalid_triggers=True)
  847. machine.walk() # Walking now
  848. machine.stop() # let's stop for a moment
  849. machine.drink() # coffee time
  850. machine.state
  851. >>> 'caffeinated'
  852. machine.walk() # we have to go faster
  853. machine.state
  854. >>> 'caffeinated_running'
  855. machine.stop() # can't stop moving!
  856. machine.state
  857. >>> 'caffeinated_running'
  858. machine.relax() # leave nested state
  859. machine.state # phew, what a ride
  860. >>> 'standing'
  861. # machine.on_enter_caffeinated_running('callback_method')
  862. ```
  863. A configuration making use of `initial` could look like this:
  864. ```python
  865. # ...
  866. states = ['standing', 'walking', {'name': 'caffeinated', 'initial': 'dithering', 'children': ['dithering', 'running']}]
  867. transitions = [
  868. ['walk', 'standing', 'walking'],
  869. ['stop', 'walking', 'standing'],
  870. # this transition will end in 'caffeinated_dithering'...
  871. ['drink', '*', 'caffeinated'],
  872. # ... that is why we do not need do specify 'caffeinated' here anymore
  873. ['walk', 'caffeinated_dithering', 'caffeinated_running'],
  874. ['relax', 'caffeinated', 'standing']
  875. ]
  876. # ...
  877. ```
  878. Some things that have to be considered when working with nested states: State *names are concatenated* with `NestedState.separator`.
  879. Currently the separator is set to underscore ('_') and therefore behaves similar to the basic machine.
  880. This means a substate `bar` from state `foo` will be known by `foo_bar`. A substate `baz` of `bar` will be referred to as `foo_bar_baz` and so on.
  881. When entering a substate, `enter` will be called for all parent states. The same is true for exiting substates.
  882. Third, nested states can overwrite transition behaviour of their parents.
  883. If a transition is not known to the current state it will be delegated to its parent.
  884. In some cases underscore as a separator is not sufficient.
  885. For instance if state names consists of more than one word and a concatenated naming such as `state_A_name_state_C` would be confusing.
  886. Setting the separator to something else than underscore changes some of the behaviour (auto_transition and setting callbacks).
  887. You can even use unicode characters if you use python 3:
  888. ```python
  889. from transitions.extensions.nesting import NestedState
  890. NestedState.separator = '↦'
  891. states = ['A', 'B',
  892. {'name': 'C', 'children':['1', '2',
  893. {'name': '3', 'children': ['a', 'b', 'c']}
  894. ]}
  895. ]
  896. transitions = [
  897. ['reset', 'C', 'A'],
  898. ['reset', 'C↦2', 'C'] # overwriting parent reset
  899. ]
  900. # we rely on auto transitions
  901. machine = Machine(states=states, transitions=transitions, initial='A')
  902. machine.to_B() # exit state A, enter state B
  903. machine.to_C() # exit B, enter C
  904. machine.to_C.s3.a() # enter C↦a; enter C↦3↦a;
  905. machine.state,
  906. >>> 'C↦3↦a'
  907. machine.to('C↦2') # not interactive; exit C↦3↦a, exit C↦3, enter C↦2
  908. machine.reset() # exit C↦2; reset C has been overwritten by C↦3
  909. machine.state
  910. >>> 'C'
  911. machine.reset() # exit C, enter A
  912. machine.state
  913. >>> 'A'
  914. # s.on_enter('C↦3↦a', 'callback_method')
  915. ```
  916. Instead of `to_C_3_a()` auto transition is called as `to_C.s3.a()`. If your substate starts with a digit, transitions adds a prefix 's' ('3' becomes 's3') to the auto transition `FunctionWrapper` to comply with the attribute naming scheme of Python.
  917. If interactive completion is not required, `to('C↦3↦a')` can be called directly. Additionally, `on_enter/exit_<<state name>>` is replaced with `on_enter/exit(state_name, callback)`.
  918. To check whether the current state is a substate of a specific state `is_state` supports the keyword `allow_substates`:
  919. ```python
  920. machine.state
  921. >>> 'C.2.a'
  922. machine.is_C() # checks for specific states
  923. >>> False
  924. machine.is_C(allow_substates=True)
  925. >>> True
  926. ```
  927. *new in 0.8.0*
  928. You can use enumerations in HSMs as well but keep in mind that `Enum` are compared by value.
  929. If you have a value more than once in a state tree those states cannot be distinguished.
  930. ```python
  931. states = [States.RED, States.YELLOW, {'name': States.GREEN, 'children': ['tick', 'tock']}]
  932. states = ['A', {'name': 'B', 'children': States, 'initial': States.GREEN}, States.GREEN]
  933. machine = HierarchicalMachine(states=states)
  934. machine.to_B()
  935. machine.is_GREEN() # returns True even though the actual state is B_GREEN
  936. ```
  937. *new in 0.8.0*
  938. `HierarchicalMachine` has been rewritten from scratch to support parallel states and better isolation of nested states.
  939. This involves some tweaks based on community feedback.
  940. To get an idea of processing order and configuration have a look at the following example:
  941. ```python
  942. from transitions.extensions.nesting import HierarchicalMachine
  943. import logging
  944. states = ['A', 'B', {'name': 'C', 'parallel': [{'name': '1', 'children': ['a', 'b', 'c'], 'initial': 'a',
  945. 'transitions': [['go', 'a', 'b']]},
  946. {'name': '2', 'children': ['x', 'y', 'z'], 'initial': 'z'}],
  947. 'transitions': [['go', '2_z', '2_x']]}]
  948. transitions = [['reset', 'C_1_b', 'B']]
  949. logging.basicConfig(level=logging.INFO)
  950. machine = HierarchicalMachine(states=states, transitions=transitions, initial='A')
  951. machine.to_C()
  952. # INFO:transitions.extensions.nesting:Exited state A
  953. # INFO:transitions.extensions.nesting:Entered state C
  954. # INFO:transitions.extensions.nesting:Entered state C_1
  955. # INFO:transitions.extensions.nesting:Entered state C_2
  956. # INFO:transitions.extensions.nesting:Entered state C_1_a
  957. # INFO:transitions.extensions.nesting:Entered state C_2_z
  958. machine.go()
  959. # INFO:transitions.extensions.nesting:Exited state C_1_a
  960. # INFO:transitions.extensions.nesting:Entered state C_1_b
  961. # INFO:transitions.extensions.nesting:Exited state C_2_z
  962. # INFO:transitions.extensions.nesting:Entered state C_2_x
  963. machine.reset()
  964. # INFO:transitions.extensions.nesting:Exited state C_1_b
  965. # INFO:transitions.extensions.nesting:Exited state C_2_x
  966. # INFO:transitions.extensions.nesting:Exited state C_1
  967. # INFO:transitions.extensions.nesting:Exited state C_2
  968. # INFO:transitions.extensions.nesting:Exited state C
  969. # INFO:transitions.extensions.nesting:Entered state B
  970. ```
  971. When using `parallel` instead of `children`, `transitions` will enter all states of the passed list at the same time.
  972. Which substate to enter is defined by `initial` which should *always* point to a direct substate.
  973. A novel feature is to define local transitions by passing the `transitions` keyword in a state definition.
  974. The above defined transition `['go', 'a', 'b']` is only valid in `C_1`.
  975. While you can reference substates as done in `['go', '2_z', '2_x']` you cannot reference parent states directly in locally defined transitions.
  976. When a parent state is exited, its children will also be exited.
  977. In addition to the processing order of transitions known from `Machine` where transitions are considered in the order they were added, `HierarchicalMachine` considers hierarchy as well.
  978. Transitions defined in substates will be evaluated first (e.g. `C_1_a` is left before `C_2_z`) and transitions defined with wildcard `*` will (for now) only add transitions to root states (in this example `A`, `B`, `C`)
  979. Starting with *0.8.0* nested states can be added directly and will issue the creation of parent states on-the-fly:
  980. ```python
  981. m = HierarchicalMachine(states=['A'], initial='A')
  982. m.add_state('B_1_a')
  983. m.to_B_1()
  984. assert m.is_B(allow_substates=True)
  985. ```
  986. #### Reuse of previously created HSMs
  987. Besides semantic order, nested states are very handy if you want to specify state machines for specific tasks and plan to reuse them.
  988. Before *0.8.0*, a `HierarchicalMachine` would not integrate the machine instance itself but the states and transitions by creating copies of them.
  989. However, since *0.8.0* states are just **referenced** which means changes in one machine's states will influence the other instance.
  990. Note that events and transitions are also copied by reference and will be shared by both instances if you do not use the `remap` keyword.
  991. ```python
  992. count_states = ['1', '2', '3', 'done']
  993. count_trans = [
  994. ['increase', '1', '2'],
  995. ['increase', '2', '3'],
  996. ['decrease', '3', '2'],
  997. ['decrease', '2', '1'],
  998. ['done', '3', 'done'],
  999. ['reset', '*', '1']
  1000. ]
  1001. counter = Machine(states=count_states, transitions=count_trans, initial='1')
  1002. counter.increase() # love my counter
  1003. states = ['waiting', 'collecting', {'name': 'counting', 'children': counter}]
  1004. transitions = [
  1005. ['collect', '*', 'collecting'],
  1006. ['wait', '*', 'waiting'],
  1007. ['count', 'collecting', 'counting']
  1008. ]
  1009. collector = Machine(states=states, transitions=transitions, initial='waiting')
  1010. collector.collect() # collecting
  1011. collector.count() # let's see what we got; counting_1
  1012. collector.increase() # counting_2
  1013. collector.increase() # counting_3
  1014. collector.done() # collector.state == counting_done
  1015. collector.wait() # collector.state == waiting
  1016. ```
  1017. If a `HierarchicalStateMachine` is passed with the `children` keyword, the initial state of this machine will be assigned to the new parent state.
  1018. In the above example we see that entering `counting` will also enter `counting_1`.
  1019. If this is undesired behaviour and the machine should rather halt in the parent state, the user can pass `initial` as `False` like `{'name': 'counting', 'children': counter, 'initial': False}`.
  1020. Sometimes you want such an embedded state collection to 'return' which means after it is done it should exit and transit to one of your super states.
  1021. To achieve this behaviour you can remap state transitions.
  1022. In the example above we would like the counter to return if the state `done` was reached.
  1023. This is done as follows:
  1024. ```python
  1025. states = ['waiting', 'collecting', {'name': 'counting', 'children': counter, 'remap': {'done': 'waiting'}}]
  1026. ... # same as above
  1027. collector.increase() # counting_3
  1028. collector.done()
  1029. collector.state
  1030. >>> 'waiting' # be aware that 'counting_done' will be removed from the state machine
  1031. ```
  1032. As mentioned above, using `remap` will **copy** events and transitions since they could not be valid in the original state machine.
  1033. If a reused state machine does not have a final state, you can of course add the transitions manually.
  1034. If 'counter' had no 'done' state, we could just add `['done', 'counter_3', 'waiting']` to achieve the same behaviour.
  1035. #### <a name="threading"></a> Threadsafe(-ish) State Machine
  1036. In cases where event dispatching is done in threads, one can use either `LockedMachine` or `LockedHierarchicalMachine` where **function access** (!sic) is secured with reentrant locks.
  1037. This does not save you from corrupting your machine by tinkering with member variables of your model or state machine.
  1038. ```python
  1039. from transitions.extensions import LockedMachine as Machine
  1040. from threading import Thread
  1041. import time
  1042. states = ['A', 'B', 'C']
  1043. machine = Machine(states=states, initial='A')
  1044. # let us assume that entering B will take some time
  1045. thread = Thread(target=machine.to_B)
  1046. thread.start()
  1047. time.sleep(0.01) # thread requires some time to start
  1048. machine.to_C() # synchronized access; won't execute before thread is done
  1049. # accessing attributes directly
  1050. thread = Thread(target=machine.to_B)
  1051. thread.start()
  1052. machine.new_attrib = 42 # not synchronized! will mess with execution order
  1053. ```
  1054. Any python context manager can be passed in via the `machine_context` keyword argument:
  1055. ```python
  1056. from transitions.extensions import LockedMachine as Machine
  1057. from threading import RLock
  1058. states = ['A', 'B', 'C']
  1059. lock1 = RLock()
  1060. lock2 = RLock()
  1061. machine = Machine(states=states, initial='A', machine_context=[lock1, lock2])
  1062. ```
  1063. Any contexts via `machine_model` will be shared between all models registered with the `Machine`.
  1064. Per-model contexts can be added as well:
  1065. ```python
  1066. lock3 = RLock()
  1067. machine.add_model(model, model_context=lock3)
  1068. ```
  1069. It's important that all user-provided context managers are re-entrant since the state machine will call them multiple
  1070. times, even in the context of a single trigger invocation.
  1071. #### <a name="async"></a> Using async callbacks
  1072. If you are using Python 3.7 or later, you can use `AsyncMachine` to work with asynchronous callbacks.
  1073. You can mix synchronous and asynchronous callbacks if you like but this may have undesired side effects.
  1074. Note that events need to be awaited and the event loop must also be handled by you.
  1075. ```python
  1076. from transitions.extensions.asyncio import AsyncMachine
  1077. import asyncio
  1078. import time
  1079. class AsyncModel:
  1080. def prepare_model(self):
  1081. print("I am synchronous.")
  1082. self.start_time = time.time()
  1083. async def before_change(self):
  1084. print("I am asynchronous and will block now for 100 milliseconds.")
  1085. await asyncio.sleep(0.1)
  1086. print("I am done waiting.")
  1087. def sync_before_change(self):
  1088. print("I am synchronous and will block the event loop (what I probably shouldn't)")
  1089. time.sleep(0.1)
  1090. print("I am done waiting synchronously.")
  1091. def after_change(self):
  1092. print(f"I am synchronous again. Execution took {int((time.time() - self.start_time) * 1000)} ms.")
  1093. transition = dict(trigger="start", source="Start", dest="Done", prepare="prepare_model",
  1094. before=["before_change"] * 5 + ["sync_before_change"],
  1095. after="after_change") # execute before function in asynchronously 5 times
  1096. model = AsyncModel()
  1097. machine = AsyncMachine(model, states=["Start", "Done"], transitions=[transition], initial='Start')
  1098. asyncio.get_event_loop().run_until_complete(model.start())
  1099. # >>> I am synchronous.
  1100. # I am asynchronous and will block now for 100 milliseconds.
  1101. # I am asynchronous and will block now for 100 milliseconds.
  1102. # I am asynchronous and will block now for 100 milliseconds.
  1103. # I am asynchronous and will block now for 100 milliseconds.
  1104. # I am asynchronous and will block now for 100 milliseconds.
  1105. # I am synchronous and will block the event loop (what I probably shouldn't)
  1106. # I am done waiting synchronously.
  1107. # I am done waiting.
  1108. # I am done waiting.
  1109. # I am done waiting.
  1110. # I am done waiting.
  1111. # I am done waiting.
  1112. # I am synchronous again. Execution took 101 ms.
  1113. assert model.is_Done()
  1114. ```
  1115. So, why do you need to use Python 3.7 or later you may ask.
  1116. Async support has been introduced earlier.
  1117. `AsyncMachine` makes use of `contextvars` to handle running callbacks when new events arrive before a transition
  1118. has been finished:
  1119. ```python
  1120. async def await_never_return():
  1121. await asyncio.sleep(100)
  1122. raise ValueError("That took too long!")
  1123. async def fix():
  1124. await m2.fix()
  1125. m1 = AsyncMachine(states=['A', 'B', 'C'], initial='A', name="m1")
  1126. m2 = AsyncMachine(states=['A', 'B', 'C'], initial='A', name="m2")
  1127. m2.add_transition(trigger='go', source='A', dest='B', before=await_never_return)
  1128. m2.add_transition(trigger='fix', source='A', dest='C')
  1129. m1.add_transition(trigger='go', source='A', dest='B', after='go')
  1130. m1.add_transition(trigger='go', source='B', dest='C', after=fix)
  1131. asyncio.get_event_loop().run_until_complete(asyncio.gather(m2.go(), m1.go()))
  1132. assert m1.state == m2.state
  1133. ```
  1134. This example illustrates actually two things:
  1135. First, that 'go' called in m1's transition from `A` to be `B` is not cancelled and second, calling `m2.fix()` will
  1136. halt the transition attempt of m2 from `A` to `B` by executing 'fix' from `A` to `C`.
  1137. This separation would not be possible without `contextvars`.
  1138. Note that `prepare` and `conditions` are NOT treated as ongoing transitions.
  1139. This means that after `conditions` have been evaluated, a transition is executed even though another event already happened.
  1140. Tasks will only be cancelled when run as a `before` callback or later.
  1141. #### <a name="state-features"></a>Adding features to states
  1142. If your superheroes need some custom behaviour, you can throw in some extra functionality by decorating machine states:
  1143. ```python
  1144. from time import sleep
  1145. from transitions import Machine
  1146. from transitions.extensions.states import add_state_features, Tags, Timeout
  1147. @add_state_features(Tags, Timeout)
  1148. class CustomStateMachine(Machine):
  1149. pass
  1150. class SocialSuperhero(object):
  1151. def __init__(self):
  1152. self.entourage = 0
  1153. def on_enter_waiting(self):
  1154. self.entourage += 1
  1155. states = [{'name': 'preparing', 'tags': ['home', 'busy']},
  1156. {'name': 'waiting', 'timeout': 1, 'on_timeout': 'go'},
  1157. {'name': 'away'}] # The city needs us!
  1158. transitions = [['done', 'preparing', 'waiting'],
  1159. ['join', 'waiting', 'waiting'], # Entering Waiting again will increase our entourage
  1160. ['go', 'waiting', 'away']] # Okay, let' move
  1161. hero = SocialSuperhero()
  1162. machine = CustomStateMachine(model=hero, states=states, transitions=transitions, initial='preparing')
  1163. assert hero.state == 'preparing' # Preparing for the night shift
  1164. assert machine.get_state(hero.state).is_busy # We are at home and busy
  1165. hero.done()
  1166. assert hero.state == 'waiting' # Waiting for fellow superheroes to join us
  1167. assert hero.entourage == 1 # It's just us so far
  1168. sleep(0.7) # Waiting...
  1169. hero.join() # Weeh, we got company
  1170. sleep(0.5) # Waiting...
  1171. hero.join() # Even more company \o/
  1172. sleep(2) # Waiting...
  1173. assert hero.state == 'away' # Impatient superhero already left the building
  1174. assert machine.get_state(hero.state).is_home is False # Yupp, not at home anymore
  1175. assert hero.entourage == 3 # At least he is not alone
  1176. ```
  1177. Currently, transitions comes equipped with the following state features:
  1178. * **Timeout** -- triggers an event after some time has passed
  1179. - keyword: `timeout` (int, optional) -- if passed, an entered state will timeout after `timeout` seconds
  1180. - keyword: `on_timeout` (string/callable, optional) -- will be called when timeout time has been reached
  1181. - will raise an `AttributeError` when `timeout` is set but `on_timeout` is not
  1182. - Note: A timeout is triggered in a thread. This implies several limitations (e.g. catching Exceptions raised in timeouts). Consider an event queue for more sophisticated applications.
  1183. * **Tags** -- adds tags to states
  1184. - keyword: `tags` (list, optional) -- assigns tags to a state
  1185. - `State.is_<tag_name>` will return `True` when the state has been tagged with `tag_name`, else `False`
  1186. * **Error** -- raises a `MachineError` when a state cannot be left
  1187. - inherits from `Tags` (if you use `Error` do not use `Tags`)
  1188. - keyword: `accepted` (bool, optional) -- marks a state as accepted
  1189. - alternatively the keyword `tags` can be passed, containing 'accepted'
  1190. - Note: Errors will only be raised if `auto_transitions` has been set to `False`. Otherwise every state can be exited with `to_<state>` methods.
  1191. * **Volatile** -- initialises an object every time a state is entered
  1192. - keyword: `volatile` (class, optional) -- every time the state is entered an object of type class will be assigned to the model. The attribute name is defined by `hook`. If omitted, an empty VolatileObject will be created instead
  1193. - keyword: `hook` (string, default='scope') -- The model's attribute name fore the temporal object.
  1194. You can write your own `State` extensions and add them the same way. Just note that `add_state_features` expects *Mixins*. This means your extension should always call the overridden methods `__init__`, `enter` and `exit`. Your extension may inherit from *State* but will also work without it.
  1195. In case you prefer to write your own custom states from scratch be aware that some state extensions *require* certain state features. `HierarchicalStateMachine` requires your custom state to be an instance of `NestedState` (`State` is not sufficient). To inject your states you can either assign them to your `Machine`'s class attribute `state_cls` or override `Machine.create_state` in case you need some specific procedures done whenever a state is created:
  1196. ```python
  1197. from transitions import Machine, State
  1198. class MyState(State):
  1199. pass
  1200. class CustomMachine(Machine):
  1201. # Use MyState as state class
  1202. state_cls = MyState
  1203. class VerboseMachine(Machine):
  1204. # `Machine._create_state` is a class method but we can
  1205. # override it to be an instance method
  1206. def _create_state(self, *args, **kwargs):
  1207. print("Creating a new state with machine '{0}'".format(self.name))
  1208. return MyState(*args, **kwargs)
  1209. ```
  1210. #### <a name="django-support"></a> Using transitions together with Django
  1211. Christian Ledermann developed `django-transitions`, a module dedicated to streamline the work with `transitions` and Django. The source code is also hosted on [Github](https://github.com/PrimarySite/django-transitions). Have a look at [the documentation](https://django-transitions.readthedocs.io/en/latest/) for usage examples.
  1212. ### <a name="bug-reports"></a>I have a [bug report/issue/question]...
  1213. For bug reports and other issues, please open an issue on GitHub.
  1214. For usage questions, post on Stack Overflow, making sure to tag your question with the `transitions` and `python` tags. Do not forget to have a look at the [extended examples](./examples)!
  1215. For any other questions, solicitations, or large unrestricted monetary gifts, email [Tal Yarkoni](mailto:tyarkoni@gmail.com).