Name | Automat JSON |
Version |
24.8.1
JSON |
| download |
home_page | None |
Summary | Self-service finite-state machines for the programmer on the go. |
upload_time | 2024-08-19 17:31:58 |
maintainer | None |
docs_url | None |
author | None |
requires_python | >=3.8 |
license | Copyright (c) 2014 Rackspace Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
keywords |
fsm
state machine
automata
|
VCS |
|
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
|
# Automat #
[![Documentation Status](https://readthedocs.org/projects/automat/badge/?version=latest)](http://automat.readthedocs.io/en/latest/)
[![Build Status](https://github.com/glyph/automat/actions/workflows/ci.yml/badge.svg?branch=trunk)](https://github.com/glyph/automat/actions/workflows/ci.yml?query=branch%3Atrunk)
[![Coverage Status](http://codecov.io/github/glyph/automat/coverage.svg?branch=trunk)](http://codecov.io/github/glyph/automat?branch=trunk)
## Self-service finite-state machines for the programmer on the go. ##
Automat is a library for concise, idiomatic Python expression of finite-state
automata (particularly deterministic finite-state transducers).
Read more here, or on [Read the Docs](https://automat.readthedocs.io/), or watch the following videos for an overview and presentation
### Why use state machines? ###
Sometimes you have to create an object whose behavior varies with its state,
but still wishes to present a consistent interface to its callers.
For example, let's say you're writing the software for a coffee machine. It
has a lid that can be opened or closed, a chamber for water, a chamber for
coffee beans, and a button for "brew".
There are a number of possible states for the coffee machine. It might or
might not have water. It might or might not have beans. The lid might be open
or closed. The "brew" button should only actually attempt to brew coffee in
one of these configurations, and the "open lid" button should only work if the
coffee is not, in fact, brewing.
With diligence and attention to detail, you can implement this correctly using
a collection of attributes on an object; `hasWater`, `hasBeans`, `isLidOpen`
and so on. However, you have to keep all these attributes consistent. As the
coffee maker becomes more complex - perhaps you add an additional chamber for
flavorings so you can make hazelnut coffee, for example - you have to keep
adding more and more checks and more and more reasoning about which
combinations of states are allowed.
Rather than adding tedious `if` checks to every single method to make sure that
each of these flags are exactly what you expect, you can use a state machine to
ensure that if your code runs at all, it will be run with all the required
values initialized, because they have to be called in the order you declare
them.
You can read about state machines and their advantages for Python programmers
in more detail [in this excellent article by Jean-Paul
Calderone](https://web.archive.org/web/20160507053658/https://clusterhq.com/2013/12/05/what-is-a-state-machine/).
### What makes Automat different? ###
There are
[dozens of libraries on PyPI implementing state machines](https://pypi.org/search/?q=finite+state+machine).
So it behooves me to say why yet another one would be a good idea.
Automat is designed around this principle: while organizing your code around
state machines is a good idea, your callers don't, and shouldn't have to, care
that you've done so. In Python, the "input" to a stateful system is a method
call; the "output" may be a method call, if you need to invoke a side effect,
or a return value, if you are just performing a computation in memory. Most
other state-machine libraries require you to explicitly create an input object,
provide that object to a generic "input" method, and then receive results,
sometimes in terms of that library's interfaces and sometimes in terms of
classes you define yourself.
For example, a snippet of the coffee-machine example above might be implemented
as follows in naive Python:
```python
class CoffeeMachine(object):
def brewButton(self) -> None:
if self.hasWater and self.hasBeans and not self.isLidOpen:
self.heatTheHeatingElement()
# ...
```
With Automat, you'd begin with a `typing.Protocol` that describes all of your
inputs:
```python
from typing import Protocol
class CoffeeBrewer(Protocol):
def brewButton(self) -> None:
"The user pressed the 'brew' button."
def putInBeans(self) -> None:
"The user put in some beans."
```
We'll then need a concrete class to contain the shared core of state shared
among the different states:
```python
from dataclasses import dataclass
@dataclass
class BrewerCore:
heatingElement: HeatingElement
```
Next, we need to describe our state machine, including all of our states. For
simplicity's sake let's say that the only two states are `noBeans` and
`haveBeans`:
```python
from automat import TypeMachineBuilder
builder = TypeMachineBuilder(CoffeeBrewer, BrewerCore)
noBeans = builder.state("noBeans")
haveBeans = builder.state("haveBeans")
```
Next we can describe a simple transition; when we put in beans, we move to the
`haveBeans` state, with no other behavior.
```python
# When we don't have beans, upon putting in beans, we will then have beans
noBeans.upon(CoffeeBrewer.putInBeans).to(haveBeans).returns(None)
```
And then another transition that we describe with a decorator, one that *does*
have some behavior, that needs to heat up the heating element to brew the
coffee:
```python
@haveBeans.upon(CoffeeBrewer.brewButton).to(noBeans)
def heatUp(inputs: CoffeeBrewer, core: BrewerCore) -> None:
"""
When we have beans, upon pressing the brew button, we will then not have
beans any more (as they have been entered into the brewing chamber) and
our output will be heating the heating element.
"""
print("Brewing the coffee...")
core.heatingElement.turnOn()
```
Then we finalize the state machine by building it, which gives us a callable
that takes a `BrewerCore` and returns a synthetic `CoffeeBrewer`
```python
newCoffeeMachine = builder.build()
```
```python
>>> coffee = newCoffeeMachine(BrewerCore(HeatingElement()))
>>> machine.putInBeans()
>>> machine.brewButton()
Brewing the coffee...
```
All of the *inputs* are provided by calling them like methods, all of the
*output behaviors* are automatically invoked when they are produced according
to the outputs specified to `upon` and all of the states are simply opaque
tokens.
Raw data
{
"_id": null,
"home_page": null,
"name": "Automat",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.8",
"maintainer_email": null,
"keywords": "fsm, state machine, automata",
"author": null,
"author_email": "Glyph <code@glyph.im>",
"download_url": "https://files.pythonhosted.org/packages/8d/2d/ede4ad7fc34ab4482389fa3369d304f2fa22e50770af706678f6a332fa82/automat-24.8.1.tar.gz",
"platform": null,
"description": "# Automat #\n\n[![Documentation Status](https://readthedocs.org/projects/automat/badge/?version=latest)](http://automat.readthedocs.io/en/latest/)\n[![Build Status](https://github.com/glyph/automat/actions/workflows/ci.yml/badge.svg?branch=trunk)](https://github.com/glyph/automat/actions/workflows/ci.yml?query=branch%3Atrunk)\n[![Coverage Status](http://codecov.io/github/glyph/automat/coverage.svg?branch=trunk)](http://codecov.io/github/glyph/automat?branch=trunk)\n\n## Self-service finite-state machines for the programmer on the go. ##\n\nAutomat is a library for concise, idiomatic Python expression of finite-state\nautomata (particularly deterministic finite-state transducers).\n\nRead more here, or on [Read the Docs](https://automat.readthedocs.io/), or watch the following videos for an overview and presentation\n\n### Why use state machines? ###\n\nSometimes you have to create an object whose behavior varies with its state,\nbut still wishes to present a consistent interface to its callers.\n\nFor example, let's say you're writing the software for a coffee machine. It\nhas a lid that can be opened or closed, a chamber for water, a chamber for\ncoffee beans, and a button for \"brew\".\n\nThere are a number of possible states for the coffee machine. It might or\nmight not have water. It might or might not have beans. The lid might be open\nor closed. The \"brew\" button should only actually attempt to brew coffee in\none of these configurations, and the \"open lid\" button should only work if the\ncoffee is not, in fact, brewing.\n\nWith diligence and attention to detail, you can implement this correctly using\na collection of attributes on an object; `hasWater`, `hasBeans`, `isLidOpen`\nand so on. However, you have to keep all these attributes consistent. As the\ncoffee maker becomes more complex - perhaps you add an additional chamber for\nflavorings so you can make hazelnut coffee, for example - you have to keep\nadding more and more checks and more and more reasoning about which\ncombinations of states are allowed.\n\nRather than adding tedious `if` checks to every single method to make sure that\neach of these flags are exactly what you expect, you can use a state machine to\nensure that if your code runs at all, it will be run with all the required\nvalues initialized, because they have to be called in the order you declare\nthem.\n\nYou can read about state machines and their advantages for Python programmers\nin more detail [in this excellent article by Jean-Paul\nCalderone](https://web.archive.org/web/20160507053658/https://clusterhq.com/2013/12/05/what-is-a-state-machine/).\n\n### What makes Automat different? ###\n\nThere are\n[dozens of libraries on PyPI implementing state machines](https://pypi.org/search/?q=finite+state+machine).\nSo it behooves me to say why yet another one would be a good idea.\n\nAutomat is designed around this principle: while organizing your code around\nstate machines is a good idea, your callers don't, and shouldn't have to, care\nthat you've done so. In Python, the \"input\" to a stateful system is a method\ncall; the \"output\" may be a method call, if you need to invoke a side effect,\nor a return value, if you are just performing a computation in memory. Most\nother state-machine libraries require you to explicitly create an input object,\nprovide that object to a generic \"input\" method, and then receive results,\nsometimes in terms of that library's interfaces and sometimes in terms of\nclasses you define yourself.\n\nFor example, a snippet of the coffee-machine example above might be implemented\nas follows in naive Python:\n\n```python\nclass CoffeeMachine(object):\n def brewButton(self) -> None:\n if self.hasWater and self.hasBeans and not self.isLidOpen:\n self.heatTheHeatingElement()\n # ...\n```\n\nWith Automat, you'd begin with a `typing.Protocol` that describes all of your\ninputs:\n\n```python\nfrom typing import Protocol\n\nclass CoffeeBrewer(Protocol):\n def brewButton(self) -> None:\n \"The user pressed the 'brew' button.\"\n def putInBeans(self) -> None:\n \"The user put in some beans.\"\n```\n\nWe'll then need a concrete class to contain the shared core of state shared\namong the different states:\n\n```python\nfrom dataclasses import dataclass\n\n@dataclass\nclass BrewerCore:\n heatingElement: HeatingElement\n```\n\nNext, we need to describe our state machine, including all of our states. For\nsimplicity's sake let's say that the only two states are `noBeans` and\n`haveBeans`:\n\n```python\nfrom automat import TypeMachineBuilder\n\nbuilder = TypeMachineBuilder(CoffeeBrewer, BrewerCore)\nnoBeans = builder.state(\"noBeans\")\nhaveBeans = builder.state(\"haveBeans\")\n```\n\nNext we can describe a simple transition; when we put in beans, we move to the\n`haveBeans` state, with no other behavior.\n\n```python\n# When we don't have beans, upon putting in beans, we will then have beans\nnoBeans.upon(CoffeeBrewer.putInBeans).to(haveBeans).returns(None)\n```\n\nAnd then another transition that we describe with a decorator, one that *does*\nhave some behavior, that needs to heat up the heating element to brew the\ncoffee:\n\n```python\n@haveBeans.upon(CoffeeBrewer.brewButton).to(noBeans)\ndef heatUp(inputs: CoffeeBrewer, core: BrewerCore) -> None:\n \"\"\"\n When we have beans, upon pressing the brew button, we will then not have\n beans any more (as they have been entered into the brewing chamber) and\n our output will be heating the heating element.\n \"\"\"\n print(\"Brewing the coffee...\")\n core.heatingElement.turnOn()\n```\n\nThen we finalize the state machine by building it, which gives us a callable\nthat takes a `BrewerCore` and returns a synthetic `CoffeeBrewer`\n\n```python\nnewCoffeeMachine = builder.build()\n```\n\n```python\n>>> coffee = newCoffeeMachine(BrewerCore(HeatingElement()))\n>>> machine.putInBeans()\n>>> machine.brewButton()\nBrewing the coffee...\n```\n\nAll of the *inputs* are provided by calling them like methods, all of the\n*output behaviors* are automatically invoked when they are produced according\nto the outputs specified to `upon` and all of the states are simply opaque\ntokens.\n",
"bugtrack_url": null,
"license": "Copyright (c) 2014 Rackspace Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ",
"summary": "Self-service finite-state machines for the programmer on the go.",
"version": "24.8.1",
"project_urls": {
"Documentation": "https://automat.readthedocs.io/",
"Source": "https://github.com/glyph/automat/"
},
"split_keywords": [
"fsm",
" state machine",
" automata"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "afcc55a32a2c98022d88812b5986d2a92c4ff3ee087e83b712ebc703bba452bf",
"md5": "d86cdc12efaf8a933b1e49a24f208f7a",
"sha256": "bf029a7bc3da1e2c24da2343e7598affaa9f10bf0ab63ff808566ce90551e02a"
},
"downloads": -1,
"filename": "Automat-24.8.1-py3-none-any.whl",
"has_sig": false,
"md5_digest": "d86cdc12efaf8a933b1e49a24f208f7a",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.8",
"size": 42585,
"upload_time": "2024-08-19T17:31:56",
"upload_time_iso_8601": "2024-08-19T17:31:56.729032Z",
"url": "https://files.pythonhosted.org/packages/af/cc/55a32a2c98022d88812b5986d2a92c4ff3ee087e83b712ebc703bba452bf/Automat-24.8.1-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "8d2dede4ad7fc34ab4482389fa3369d304f2fa22e50770af706678f6a332fa82",
"md5": "c023f8848366053a76f99cffba3ea34e",
"sha256": "b34227cf63f6325b8ad2399ede780675083e439b20c323d376373d8ee6306d88"
},
"downloads": -1,
"filename": "automat-24.8.1.tar.gz",
"has_sig": false,
"md5_digest": "c023f8848366053a76f99cffba3ea34e",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8",
"size": 128679,
"upload_time": "2024-08-19T17:31:58",
"upload_time_iso_8601": "2024-08-19T17:31:58.187352Z",
"url": "https://files.pythonhosted.org/packages/8d/2d/ede4ad7fc34ab4482389fa3369d304f2fa22e50770af706678f6a332fa82/automat-24.8.1.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-08-19 17:31:58",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "glyph",
"github_project": "automat",
"travis_ci": false,
"coveralls": true,
"github_actions": true,
"tox": true,
"lcname": "automat"
}