You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

488 lines
18 KiB

4 years ago
  1. Metadata-Version: 2.0
  2. Name: Automat
  3. Version: 0.7.0
  4. Summary: Self-service finite-state machines for the programmer on the go.
  5. Home-page: https://github.com/glyph/Automat
  6. Author: Glyph
  7. Author-email: glyph@twistedmatrix.com
  8. License: MIT
  9. Keywords: fsm finite state machine automata
  10. Platform: UNKNOWN
  11. Classifier: Intended Audience :: Developers
  12. Classifier: License :: OSI Approved :: MIT License
  13. Classifier: Operating System :: OS Independent
  14. Classifier: Programming Language :: Python
  15. Classifier: Programming Language :: Python :: 2
  16. Classifier: Programming Language :: Python :: 2.7
  17. Classifier: Programming Language :: Python :: 3
  18. Classifier: Programming Language :: Python :: 3.3
  19. Classifier: Programming Language :: Python :: 3.4
  20. Classifier: Programming Language :: Python :: 3.5
  21. Classifier: Programming Language :: Python :: 3.6
  22. Provides-Extra: visualize
  23. Requires-Dist: attrs (>=16.1.0)
  24. Requires-Dist: six
  25. Provides-Extra: visualize
  26. Requires-Dist: graphviz (>0.5.1); extra == 'visualize'
  27. Requires-Dist: Twisted (>=16.1.1); extra == 'visualize'
  28. Automat
  29. =======
  30. .. image:: https://readthedocs.org/projects/automat/badge/?version=stable
  31. :target: http://automat.readthedocs.io/en/latest/
  32. :alt: Documentation Status
  33. .. image:: https://travis-ci.org/glyph/automat.svg?branch=master
  34. :target: https://travis-ci.org/glyph/automat
  35. :alt: Build Status
  36. .. image:: https://coveralls.io/repos/glyph/automat/badge.png
  37. :target: https://coveralls.io/r/glyph/automat
  38. :alt: Coverage Status
  39. Self-service finite-state machines for the programmer on the go.
  40. ----------------------------------------------------------------
  41. Automat is a library for concise, idiomatic Python expression of finite-state
  42. automata (particularly deterministic finite-state transducers).
  43. Read more here, or on `Read the Docs <https://automat.readthedocs.io/>`_\ , or watch the following videos for an overview and presentation
  44. Overview and presentation by **Glyph Lefkowitz** at the first talk of the first Pyninsula meetup, on February 21st, 2017:
  45. .. image:: https://img.youtube.com/vi/0wOZBpD1VVk/0.jpg
  46. :target: https://www.youtube.com/watch?v=0wOZBpD1VVk
  47. :alt: Glyph Lefkowitz - Automat - Pyninsula #0
  48. Presentation by **Clinton Roy** at PyCon Australia, on August 6th 2017:
  49. .. image:: https://img.youtube.com/vi/TedUKXhu9kE/0.jpg
  50. :target: https://www.youtube.com/watch?v=TedUKXhu9kE
  51. :alt: Clinton Roy - State Machines - Pycon Australia 2017
  52. Why use state machines?
  53. ^^^^^^^^^^^^^^^^^^^^^^^
  54. Sometimes you have to create an object whose behavior varies with its state,
  55. but still wishes to present a consistent interface to its callers.
  56. For example, let's say you're writing the software for a coffee machine. It
  57. has a lid that can be opened or closed, a chamber for water, a chamber for
  58. coffee beans, and a button for "brew".
  59. There are a number of possible states for the coffee machine. It might or
  60. might not have water. It might or might not have beans. The lid might be open
  61. or closed. The "brew" button should only actually attempt to brew coffee in
  62. one of these configurations, and the "open lid" button should only work if the
  63. coffee is not, in fact, brewing.
  64. With diligence and attention to detail, you can implement this correctly using
  65. a collection of attributes on an object; ``has_water``\ , ``has_beans``\ ,
  66. ``is_lid_open`` and so on. However, you have to keep all these attributes
  67. consistent. As the coffee maker becomes more complex - perhaps you add an
  68. additional chamber for flavorings so you can make hazelnut coffee, for
  69. example - you have to keep adding more and more checks and more and more
  70. reasoning about which combinations of states are allowed.
  71. Rather than adding tedious 'if' checks to every single method to make sure that
  72. each of these flags are exactly what you expect, you can use a state machine to
  73. ensure that if your code runs at all, it will be run with all the required
  74. values initialized, because they have to be called in the order you declare
  75. them.
  76. You can read about state machines and their advantages for Python programmers
  77. in considerably more detail
  78. `in this excellent series of articles from ClusterHQ <https://clusterhq.com/blog/what-is-a-state-machine/>`_.
  79. What makes Automat different?
  80. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  81. There are
  82. `dozens of libraries on PyPI implementing state machines <https://pypi.org/search/?q=finite+state+machine>`_.
  83. So it behooves me to say why yet another one would be a good idea.
  84. Automat is designed around this principle: while organizing your code around
  85. state machines is a good idea, your callers don't, and shouldn't have to, care
  86. that you've done so. In Python, the "input" to a stateful system is a method
  87. call; the "output" may be a method call, if you need to invoke a side effect,
  88. or a return value, if you are just performing a computation in memory. Most
  89. other state-machine libraries require you to explicitly create an input object,
  90. provide that object to a generic "input" method, and then receive results,
  91. sometimes in terms of that library's interfaces and sometimes in terms of
  92. classes you define yourself.
  93. For example, a snippet of the coffee-machine example above might be implemented
  94. as follows in naive Python:
  95. .. code-block:: python
  96. class CoffeeMachine(object):
  97. def brew_button(self):
  98. if self.has_water and self.has_beans and not self.is_lid_open:
  99. self.heat_the_heating_element()
  100. # ...
  101. With Automat, you'd create a class with a ``MethodicalMachine`` attribute:
  102. .. code-block:: python
  103. from automat import MethodicalMachine
  104. class CoffeeBrewer(object):
  105. _machine = MethodicalMachine()
  106. and then you would break the above logic into two pieces - the ``brew_button``
  107. *input*\ , declared like so:
  108. .. code-block:: python
  109. @_machine.input()
  110. def brew_button(self):
  111. "The user pressed the 'brew' button."
  112. It wouldn't do any good to declare a method *body* on this, however, because
  113. input methods don't actually execute their bodies when called; doing actual
  114. work is the *output*\ 's job:
  115. .. code-block:: python
  116. @_machine.output()
  117. def _heat_the_heating_element(self):
  118. "Heat up the heating element, which should cause coffee to happen."
  119. self._heating_element.turn_on()
  120. As well as a couple of *states* - and for simplicity's sake let's say that the
  121. only two states are ``have_beans`` and ``dont_have_beans``\ :
  122. .. code-block:: python
  123. @_machine.state()
  124. def have_beans(self):
  125. "In this state, you have some beans."
  126. @_machine.state(initial=True)
  127. def dont_have_beans(self):
  128. "In this state, you don't have any beans."
  129. ``dont_have_beans`` is the ``initial`` state because ``CoffeeBrewer`` starts without beans
  130. in it.
  131. (And another input to put some beans in:)
  132. .. code-block:: python
  133. @_machine.input()
  134. def put_in_beans(self):
  135. "The user put in some beans."
  136. Finally, you hook everything together with the ``upon`` method of the functions
  137. decorated with ``_machine.state``\ :
  138. .. code-block:: python
  139. # When we don't have beans, upon putting in beans, we will then have beans
  140. # (and produce no output)
  141. dont_have_beans.upon(put_in_beans, enter=have_beans, outputs=[])
  142. # When we have beans, upon pressing the brew button, we will then not have
  143. # beans any more (as they have been entered into the brewing chamber) and
  144. # our output will be heating the heating element.
  145. have_beans.upon(brew_button, enter=dont_have_beans,
  146. outputs=[_heat_the_heating_element])
  147. To *users* of this coffee machine class though, it still looks like a POPO
  148. (Plain Old Python Object):
  149. .. code-block:: python
  150. >>> coffee_machine = CoffeeMachine()
  151. >>> coffee_machine.put_in_beans()
  152. >>> coffee_machine.brew_button()
  153. All of the *inputs* are provided by calling them like methods, all of the
  154. *outputs* are automatically invoked when they are produced according to the
  155. outputs specified to ``upon`` and all of the states are simply opaque tokens -
  156. although the fact that they're defined as methods like inputs and outputs
  157. allows you to put docstrings on them easily to document them.
  158. How do I get the current state of a state machine?
  159. --------------------------------------------------
  160. Don't do that.
  161. One major reason for having a state machine is that you want the callers of the
  162. state machine to just provide the appropriate input to the machine at the
  163. appropriate time, and *not have to check themselves* what state the machine is
  164. in. So if you are tempted to write some code like this:
  165. .. code-block:: python
  166. if connection_state_machine.state == "CONNECTED":
  167. connection_state_machine.send_message()
  168. else:
  169. print("not connected")
  170. Instead, just make your calling code do this:
  171. .. code-block:: python
  172. connection_state_machine.send_message()
  173. and then change your state machine to look like this:
  174. .. code-block:: python
  175. @_machine.state()
  176. def connected(self):
  177. "connected"
  178. @_machine.state()
  179. def not_connected(self):
  180. "not connected"
  181. @_machine.input()
  182. def send_message(self):
  183. "send a message"
  184. @_machine.output()
  185. def _actually_send_message(self):
  186. self._transport.send(b"message")
  187. @_machine.output()
  188. def _report_sending_failure(self):
  189. print("not connected")
  190. connected.upon(send_message, enter=connected, [_actually_send_message])
  191. not_connected.upon(send_message, enter=not_connected, [_report_sending_failure])
  192. so that the responsibility for knowing which state the state machine is in
  193. remains within the state machine itself.
  194. Input for Inputs and Output for Outputs
  195. ---------------------------------------
  196. Quite often you want to be able to pass parameters to your methods, as well as
  197. inspecting their results. For example, when you brew the coffee, you might
  198. expect a cup of coffee to result, and you would like to see what kind of coffee
  199. it is. And if you were to put delicious hand-roasted small-batch artisanal
  200. beans into the machine, you would expect a *better* cup of coffee than if you
  201. were to use mass-produced beans. You would do this in plain old Python by
  202. adding a parameter, so that's how you do it in Automat as well.
  203. .. code-block:: python
  204. @_machine.input()
  205. def put_in_beans(self, beans):
  206. "The user put in some beans."
  207. However, one important difference here is that *we can't add any
  208. implementation code to the input method*. Inputs are purely a declaration of
  209. the interface; the behavior must all come from outputs. Therefore, the change
  210. in the state of the coffee machine must be represented as an output. We can
  211. add an output method like this:
  212. .. code-block:: python
  213. @_machine.output()
  214. def _save_beans(self, beans):
  215. "The beans are now in the machine; save them."
  216. self._beans = beans
  217. and then connect it to the ``put_in_beans`` by changing the transition from
  218. ``dont_have_beans`` to ``have_beans`` like so:
  219. .. code-block:: python
  220. dont_have_beans.upon(put_in_beans, enter=have_beans,
  221. outputs=[_save_beans])
  222. Now, when you call:
  223. .. code-block:: python
  224. coffee_machine.put_in_beans("real good beans")
  225. the machine will remember the beans for later.
  226. So how do we get the beans back out again? One of our outputs needs to have a
  227. return value. It would make sense if our ``brew_button`` method returned the cup
  228. of coffee that it made, so we should add an output. So, in addition to heating
  229. the heating element, let's add a return value that describes the coffee. First
  230. a new output:
  231. .. code-block:: python
  232. @_machine.output()
  233. def _describe_coffee(self):
  234. return "A cup of coffee made with {}.".format(self._beans)
  235. Note that we don't need to check first whether ``self._beans`` exists or not,
  236. because we can only reach this output method if the state machine says we've
  237. gone through a set of states that sets this attribute.
  238. Now, we need to hook up ``_describe_coffee`` to the process of brewing, so change
  239. the brewing transition to:
  240. .. code-block:: python
  241. have_beans.upon(brew_button, enter=dont_have_beans,
  242. outputs=[_heat_the_heating_element,
  243. _describe_coffee])
  244. Now, we can call it:
  245. .. code-block:: python
  246. >>> coffee_machine.brew_button()
  247. [None, 'A cup of coffee made with real good beans.']
  248. Except... wait a second, what's that ``None`` doing there?
  249. Since every input can produce multiple outputs, in automat, the default return
  250. value from every input invocation is a ``list``. In this case, we have both
  251. ``_heat_the_heating_element`` and ``_describe_coffee`` outputs, so we're seeing
  252. both of their return values. However, this can be customized, with the
  253. ``collector`` argument to ``upon``\ ; the ``collector`` is a callable which takes an
  254. iterable of all the outputs' return values and "collects" a single return value
  255. to return to the caller of the state machine.
  256. In this case, we only care about the last output, so we can adjust the call to
  257. ``upon`` like this:
  258. .. code-block:: python
  259. have_beans.upon(brew_button, enter=dont_have_beans,
  260. outputs=[_heat_the_heating_element,
  261. _describe_coffee],
  262. collector=lambda iterable: list(iterable)[-1]
  263. )
  264. And now, we'll get just the return value we want:
  265. .. code-block:: python
  266. >>> coffee_machine.brew_button()
  267. 'A cup of coffee made with real good beans.'
  268. If I can't get the state of the state machine, how can I save it to (a database, an API response, a file on disk...)
  269. --------------------------------------------------------------------------------------------------------------------
  270. There are APIs for serializing the state machine.
  271. First, you have to decide on a persistent representation of each state, via the
  272. ``serialized=`` argument to the ``MethodicalMachine.state()`` decorator.
  273. Let's take this very simple "light switch" state machine, which can be on or
  274. off, and flipped to reverse its state:
  275. .. code-block:: python
  276. class LightSwitch(object):
  277. _machine = MethodicalMachine()
  278. @_machine.state(serialized="on")
  279. def on_state(self):
  280. "the switch is on"
  281. @_machine.state(serialized="off", initial=True)
  282. def off_state(self):
  283. "the switch is off"
  284. @_machine.input()
  285. def flip(self):
  286. "flip the switch"
  287. on_state.upon(flip, enter=off_state, outputs=[])
  288. off_state.upon(flip, enter=on_state, outputs=[])
  289. In this case, we've chosen a serialized representation for each state via the
  290. ``serialized`` argument. The on state is represented by the string ``"on"``\ , and
  291. the off state is represented by the string ``"off"``.
  292. Now, let's just add an input that lets us tell if the switch is on or not.
  293. .. code-block:: python
  294. @_machine.input()
  295. def query_power(self):
  296. "return True if powered, False otherwise"
  297. @_machine.output()
  298. def _is_powered(self):
  299. return True
  300. @_machine.output()
  301. def _not_powered(self):
  302. return False
  303. on_state.upon(query_power, enter=on_state, outputs=[_is_powered],
  304. collector=next)
  305. off_state.upon(query_power, enter=off_state, outputs=[_not_powered],
  306. collector=next)
  307. To save the state, we have the ``MethodicalMachine.serializer()`` method. A
  308. method decorated with ``@serializer()`` gets an extra argument injected at the
  309. beginning of its argument list: the serialized identifier for the state. In
  310. this case, either ``"on"`` or ``"off"``. Since state machine output methods can
  311. also affect other state on the object, a serializer method is expected to
  312. return *all* relevant state for serialization.
  313. For our simple light switch, such a method might look like this:
  314. .. code-block:: python
  315. @_machine.serializer()
  316. def save(self, state):
  317. return {"is-it-on": state}
  318. Serializers can be public methods, and they can return whatever you like. If
  319. necessary, you can have different serializers - just multiple methods decorated
  320. with ``@_machine.serializer()`` - for different formats; return one data-structure
  321. for JSON, one for XML, one for a database row, and so on.
  322. When it comes time to unserialize, though, you generally want a private method,
  323. because an unserializer has to take a not-fully-initialized instance and
  324. populate it with state. It is expected to *return* the serialized machine
  325. state token that was passed to the serializer, but it can take whatever
  326. arguments you like. Of course, in order to return that, it probably has to
  327. take it somewhere in its arguments, so it will generally take whatever a paired
  328. serializer has returned as an argument.
  329. So our unserializer would look like this:
  330. .. code-block:: python
  331. @_machine.unserializer()
  332. def _restore(self, blob):
  333. return blob["is-it-on"]
  334. Generally you will want a classmethod deserialization constructor which you
  335. write yourself to call this, so that you know how to create an instance of your
  336. own object, like so:
  337. .. code-block:: python
  338. @classmethod
  339. def from_blob(cls, blob):
  340. self = cls()
  341. self._restore(blob)
  342. return self
  343. Saving and loading our ``LightSwitch`` along with its state-machine state can now
  344. be accomplished as follows:
  345. .. code-block:: python
  346. >>> switch1 = LightSwitch()
  347. >>> switch1.query_power()
  348. False
  349. >>> switch1.flip()
  350. []
  351. >>> switch1.query_power()
  352. True
  353. >>> blob = switch1.save()
  354. >>> switch2 = LightSwitch.from_blob(blob)
  355. >>> switch2.query_power()
  356. True
  357. More comprehensive (tested, working) examples are present in ``docs/examples``.
  358. Go forth and machine all the state!