{"id":26483549,"url":"https://github.com/faucetsdn/python3-transitions","last_synced_at":"2025-03-20T04:55:56.143Z","repository":{"id":45869409,"uuid":"161411492","full_name":"faucetsdn/python3-transitions","owner":"faucetsdn","description":null,"archived":false,"fork":false,"pushed_at":"2021-12-01T03:09:32.000Z","size":2421,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":4,"default_branch":"master","last_synced_at":"2024-04-16T04:04:16.151Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/faucetsdn.png","metadata":{"files":{"readme":"README.md","changelog":"Changelog.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-12-12T00:37:21.000Z","updated_at":"2021-12-01T03:35:28.000Z","dependencies_parsed_at":"2022-09-10T03:31:57.447Z","dependency_job_id":null,"html_url":"https://github.com/faucetsdn/python3-transitions","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/faucetsdn%2Fpython3-transitions","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/faucetsdn%2Fpython3-transitions/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/faucetsdn%2Fpython3-transitions/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/faucetsdn%2Fpython3-transitions/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/faucetsdn","download_url":"https://codeload.github.com/faucetsdn/python3-transitions/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244554064,"owners_count":20471173,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-03-20T04:55:55.391Z","updated_at":"2025-03-20T04:55:56.123Z","avatar_url":"https://github.com/faucetsdn.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# \u003ca name=\"transitions-module\"\u003e\u003c/a\u003e transitions\r\n[![Version](https://img.shields.io/badge/version-v0.8.9-orange.svg)](https://github.com/pytransitions/transitions)\r\n[![Build Status](https://github.com/pytransitions/transitions/actions/workflows/pytest.yml/badge.svg)](https://github.com/pytransitions/transitions/actions?query=workflow%3Apytest)\r\n[![Coverage Status](https://coveralls.io/repos/pytransitions/transitions/badge.svg?branch=master\u0026service=github)](https://coveralls.io/github/pytransitions/transitions?branch=master)\r\n[![PyPi](https://img.shields.io/pypi/v/transitions.svg)](https://pypi.org/project/transitions)\r\n[![GitHub commits](https://img.shields.io/github/commits-since/pytransitions/transitions/0.8.8.svg)](https://github.com/pytransitions/transitions/compare/0.8.8...master)\r\n[![License](https://img.shields.io/github/license/pytransitions/transitions.svg)](LICENSE)\r\n[![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/pytransitions/transitions/master?filepath=examples%2FPlayground.ipynb)\r\n\u003c!-- [![Pylint](https://img.shields.io/badge/pylint-9.71%2F10-green.svg)](https://github.com/pytransitions/transitions) --\u003e\r\n\u003c!--[![Name](Image)](Link)--\u003e\r\n\r\nA lightweight, object-oriented state machine implementation in Python with many extensions. Compatible with Python 2.7+ and 3.0+.\r\n\r\n## Installation\r\n\r\n    pip install transitions\r\n\r\n... or clone the repo from GitHub and then:\r\n\r\n    python setup.py install\r\n\r\n\r\n## Table of Contents\r\n- [Quickstart](#quickstart)\r\n- [Non-Quickstart](#the-non-quickstart)\r\n    - [Basic initialization](#basic-initialization)\r\n    - [States](#states)\r\n        - [Callbacks](#state-callbacks)\r\n        - [Checking state](#checking-state)\r\n        - [Enumerations](#enum-state)\r\n    - [Transitions](#transitions)\r\n        - [Automatic transitions](#automatic-transitions-for-all-states)\r\n        - [Transitioning from multiple states](#transitioning-from-multiple-states)\r\n        - [Reflexive transitions from multiple states](#reflexive-from-multiple-states)\r\n        - [Internal transitions](#internal-transitions)\r\n        - [Ordered transitions](#ordered-transitions)\r\n        - [Queued transitions](#queued-transitions)\r\n        - [Conditional transitions](#conditional-transitions)\r\n        - [Callbacks](#transition-callbacks)\r\n    - [Callable resolution](#resolution)\r\n    - [Callback execution order](#execution-order)\r\n    - [Passing data](#passing-data)\r\n    - [Alternative initialization patterns](#alternative-initialization-patterns)\r\n    - [Logging](#logging)\r\n    - [(Re-)Storing machine instances](#restoring)\r\n    - [Extensions](#extensions)\r\n        - [Diagrams](#diagrams)\r\n        - [Hierarchical State Machine](#hsm)\r\n        - [Threading](#threading)\r\n        - [Async](#async)\r\n        - [State features](#state-features)\r\n        - [Django](#django-support)\r\n    - [Bug reports etc.](#bug-reports)\r\n\r\n\r\n## Quickstart\r\n\r\nThey say [a good example is worth](https://www.google.com/webhp?ie=UTF-8#q=%22a+good+example+is+worth%22\u0026start=20) 100 pages of API documentation, a million directives, or a thousand words.\r\n\r\nWell, \"they\" probably lie... but here's an example anyway:\r\n\r\n```python\r\nfrom transitions import Machine\r\nimport random\r\n\r\nclass NarcolepticSuperhero(object):\r\n\r\n    # Define some states. Most of the time, narcoleptic superheroes are just like\r\n    # everyone else. Except for...\r\n    states = ['asleep', 'hanging out', 'hungry', 'sweaty', 'saving the world']\r\n\r\n    def __init__(self, name):\r\n\r\n        # No anonymous superheroes on my watch! Every narcoleptic superhero gets\r\n        # a name. Any name at all. SleepyMan. SlumberGirl. You get the idea.\r\n        self.name = name\r\n\r\n        # What have we accomplished today?\r\n        self.kittens_rescued = 0\r\n\r\n        # Initialize the state machine\r\n        self.machine = Machine(model=self, states=NarcolepticSuperhero.states, initial='asleep')\r\n\r\n        # Add some transitions. We could also define these using a static list of\r\n        # dictionaries, as we did with states above, and then pass the list to\r\n        # the Machine initializer as the transitions= argument.\r\n\r\n        # At some point, every superhero must rise and shine.\r\n        self.machine.add_transition(trigger='wake_up', source='asleep', dest='hanging out')\r\n\r\n        # Superheroes need to keep in shape.\r\n        self.machine.add_transition('work_out', 'hanging out', 'hungry')\r\n\r\n        # Those calories won't replenish themselves!\r\n        self.machine.add_transition('eat', 'hungry', 'hanging out')\r\n\r\n        # Superheroes are always on call. ALWAYS. But they're not always\r\n        # dressed in work-appropriate clothing.\r\n        self.machine.add_transition('distress_call', '*', 'saving the world',\r\n                         before='change_into_super_secret_costume')\r\n\r\n        # When they get off work, they're all sweaty and disgusting. But before\r\n        # they do anything else, they have to meticulously log their latest\r\n        # escapades. Because the legal department says so.\r\n        self.machine.add_transition('complete_mission', 'saving the world', 'sweaty',\r\n                         after='update_journal')\r\n\r\n        # Sweat is a disorder that can be remedied with water.\r\n        # Unless you've had a particularly long day, in which case... bed time!\r\n        self.machine.add_transition('clean_up', 'sweaty', 'asleep', conditions=['is_exhausted'])\r\n        self.machine.add_transition('clean_up', 'sweaty', 'hanging out')\r\n\r\n        # Our NarcolepticSuperhero can fall asleep at pretty much any time.\r\n        self.machine.add_transition('nap', '*', 'asleep')\r\n\r\n    def update_journal(self):\r\n        \"\"\" Dear Diary, today I saved Mr. Whiskers. Again. \"\"\"\r\n        self.kittens_rescued += 1\r\n\r\n    @property\r\n    def is_exhausted(self):\r\n        \"\"\" Basically a coin toss. \"\"\"\r\n        return random.random() \u003c 0.5\r\n\r\n    def change_into_super_secret_costume(self):\r\n        print(\"Beauty, eh?\")\r\n```\r\n\r\nThere, now you've baked a state machine into `NarcolepticSuperhero`. Let's take him/her/it out for a spin...\r\n\r\n```python\r\n\u003e\u003e\u003e batman = NarcolepticSuperhero(\"Batman\")\r\n\u003e\u003e\u003e batman.state\r\n'asleep'\r\n\r\n\u003e\u003e\u003e batman.wake_up()\r\n\u003e\u003e\u003e batman.state\r\n'hanging out'\r\n\r\n\u003e\u003e\u003e batman.nap()\r\n\u003e\u003e\u003e batman.state\r\n'asleep'\r\n\r\n\u003e\u003e\u003e batman.clean_up()\r\nMachineError: \"Can't trigger event clean_up from state asleep!\"\r\n\r\n\u003e\u003e\u003e batman.wake_up()\r\n\u003e\u003e\u003e batman.work_out()\r\n\u003e\u003e\u003e batman.state\r\n'hungry'\r\n\r\n# Batman still hasn't done anything useful...\r\n\u003e\u003e\u003e batman.kittens_rescued\r\n0\r\n\r\n# We now take you live to the scene of a horrific kitten entreement...\r\n\u003e\u003e\u003e batman.distress_call()\r\n'Beauty, eh?'\r\n\u003e\u003e\u003e batman.state\r\n'saving the world'\r\n\r\n# Back to the crib.\r\n\u003e\u003e\u003e batman.complete_mission()\r\n\u003e\u003e\u003e batman.state\r\n'sweaty'\r\n\r\n\u003e\u003e\u003e batman.clean_up()\r\n\u003e\u003e\u003e batman.state\r\n'asleep'   # Too tired to shower!\r\n\r\n# Another productive day, Alfred.\r\n\u003e\u003e\u003e batman.kittens_rescued\r\n1\r\n```\r\n\r\nWhile we cannot read the mind of the actual batman, we surely can visualize the current state of our `NarcolepticSuperhero`.\r\n\r\n![batman diagram](https://user-images.githubusercontent.com/205986/104932302-c2f24580-59a7-11eb-8963-5dce738b9305.png)\r\n\r\nHave a look at the [Diagrams](#diagrams) extensions if you want to know how.\r\n\r\n## The non-quickstart\r\n\r\n### Basic initialization\r\n\r\nGetting 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:\r\n\r\n```python\r\nclass Matter(object):\r\n    pass\r\n\r\nlump = Matter()\r\n```\r\n\r\nYou can initialize a (_minimal_) working state machine bound to `lump` like this:\r\n\r\n```python\r\nfrom transitions import Machine\r\nmachine = Machine(model=lump, states=['solid', 'liquid', 'gas', 'plasma'], initial='solid')\r\n\r\n# Lump now has state!\r\nlump.state\r\n\u003e\u003e\u003e 'solid'\r\n```\r\n\r\nI 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!\r\n\r\nLet's try again.\r\n\r\n```python\r\n# The states\r\nstates=['solid', 'liquid', 'gas', 'plasma']\r\n\r\n# And some transitions between states. We're lazy, so we'll leave out\r\n# the inverse phase transitions (freezing, condensation, etc.).\r\ntransitions = [\r\n    { 'trigger': 'melt', 'source': 'solid', 'dest': 'liquid' },\r\n    { 'trigger': 'evaporate', 'source': 'liquid', 'dest': 'gas' },\r\n    { 'trigger': 'sublimate', 'source': 'solid', 'dest': 'gas' },\r\n    { 'trigger': 'ionize', 'source': 'gas', 'dest': 'plasma' }\r\n]\r\n\r\n# Initialize\r\nmachine = Machine(lump, states=states, transitions=transitions, initial='liquid')\r\n\r\n# Now lump maintains state...\r\nlump.state\r\n\u003e\u003e\u003e 'liquid'\r\n\r\n# And that state can change...\r\nlump.evaporate()\r\nlump.state\r\n\u003e\u003e\u003e 'gas'\r\nlump.trigger('ionize')\r\nlump.state\r\n\u003e\u003e\u003e 'plasma'\r\n```\r\n\r\nNotice 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`).\r\nTo be more precise, your model **should not** already contain methods with the same name as event triggers since `transitions` will only attach convenience methods to your model if the spot is not already taken.\r\nIf you want to modify that behaviour, have a look at the [FAQ](examples/Frequently%20asked%20questions.ipynb).\r\nFurthermore, there is a method called `trigger` now attached to your model (if it hasn't been there before).\r\nThis method lets you execute transitions by name in case dynamic triggering is required.\r\n\r\n### \u003ca name=\"states\"\u003e\u003c/a\u003eStates\r\n\r\nThe 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.\r\n\r\nYou can initialize and modify States in a number of ways. Specifically, you can:\r\n\r\n- pass a string to the `Machine` initializer giving the name(s) of the state(s), or\r\n- directly initialize each new `State` object, or\r\n- pass a dictionary with initialization arguments\r\n\r\nThe following snippets illustrate several ways to achieve the same goal:\r\n\r\n```python\r\n# import Machine and State class\r\nfrom transitions import Machine, State\r\n\r\n# Create a list of 3 states to pass to the Machine\r\n# initializer. We can mix types; in this case, we\r\n# pass one State, one string, and one dict.\r\nstates = [\r\n    State(name='solid'),\r\n    'liquid',\r\n    { 'name': 'gas'}\r\n    ]\r\nmachine = Machine(lump, states)\r\n\r\n# This alternative example illustrates more explicit\r\n# addition of states and state callbacks, but the net\r\n# result is identical to the above.\r\nmachine = Machine(lump)\r\nsolid = State('solid')\r\nliquid = State('liquid')\r\ngas = State('gas')\r\nmachine.add_states([solid, liquid, gas])\r\n```\r\n\r\nStates 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.\r\n\r\n#### \u003ca name=\"state-callbacks\"\u003e\u003c/a\u003eCallbacks\r\nA `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 by passing them to a `State` object constructor, in a state property dictionary, or add them later. \r\n\r\nFor 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.\r\n\r\n```python\r\n# Our old Matter class, now with  a couple of new methods we\r\n# can trigger when entering or exit states.\r\nclass Matter(object):\r\n    def say_hello(self): print(\"hello, new state!\")\r\n    def say_goodbye(self): print(\"goodbye, old state!\")\r\n\r\nlump = Matter()\r\n\r\n# Same states as above, but now we give StateA an exit callback\r\nstates = [\r\n    State(name='solid', on_exit=['say_goodbye']),\r\n    'liquid',\r\n    { 'name': 'gas', 'on_exit': ['say_goodbye']}\r\n    ]\r\n\r\nmachine = Machine(lump, states=states)\r\nmachine.add_transition('sublimate', 'solid', 'gas')\r\n\r\n# Callbacks can also be added after initialization using\r\n# the dynamically added on_enter_ and on_exit_ methods.\r\n# Note that the initial call to add the callback is made\r\n# on the Machine and not on the model.\r\nmachine.on_enter_gas('say_hello')\r\n\r\n# Test out the callbacks...\r\nmachine.set_state('solid')\r\nlump.sublimate()\r\n\u003e\u003e\u003e 'goodbye, old state!'\r\n\u003e\u003e\u003e 'hello, new state!'\r\n```\r\n\r\nNote 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.)\r\n\r\nIn 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:\r\n\r\n```python\r\nclass Matter(object):\r\n    def say_hello(self): print(\"hello, new state!\")\r\n    def say_goodbye(self): print(\"goodbye, old state!\")\r\n    def on_enter_A(self): print(\"We've just entered state A!\")\r\n\r\nlump = Matter()\r\nmachine = Machine(lump, states=['A', 'B', 'C'])\r\n```\r\n\r\nNow, any time `lump` transitions to state `A`, the `on_enter_A()` method defined in the `Matter` class will fire.\r\n\r\n#### \u003ca name=\"checking-state\"\u003e\u003c/a\u003eChecking state\r\n\r\nYou can always check the current state of the model by either:\r\n\r\n- inspecting the `.state` attribute, or\r\n- calling `is_«state name»()`\r\n\r\nAnd 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.\r\n\r\n```python\r\nlump.state\r\n\u003e\u003e\u003e 'solid'\r\nlump.is_gas()\r\n\u003e\u003e\u003e False\r\nlump.is_solid()\r\n\u003e\u003e\u003e True\r\nmachine.get_state(lump.state).name\r\n\u003e\u003e\u003e 'solid'\r\n```\r\n\r\nIf you'd like you can choose your own state attribute name by passing the `model_attribute` argument while initializing the `Machine`. This will also change the name of `is_«state name»()` to `is_«model_attribute»_«state name»()` though. Similarly, auto transitions will be named `to_«model_attribute»_«state name»()` instead of `to_«state name»()`. This is done to allow multiple machines to work on the same model with individual state attribute names.\r\n\r\n```python\r\nlump = Matter()\r\nmachine = Machine(lump, states=['solid', 'liquid', 'gas'],  model_attribute='matter_state', initial='solid')\r\nlump.matter_state\r\n\u003e\u003e\u003e 'solid'\r\n# with a custom 'model_attribute', states can also be checked like this:\r\nlump.is_matter_state_solid()\r\n\u003e\u003e\u003e True\r\nlump.to_matter_state_gas()\r\n\u003e\u003e\u003e True\r\n```\r\n\r\n#### \u003ca name=\"enum-state\"\u003e\u003c/a\u003eEnumerations\r\n\r\nSo far we have seen how we can give state names and use these names to work with our state machine.\r\nIf 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:\r\n\r\n```python\r\nimport enum  # Python 2.7 users need to have 'enum34' installed\r\nfrom transitions import Machine\r\n\r\nclass States(enum.Enum):\r\n    ERROR = 0\r\n    RED = 1\r\n    YELLOW = 2\r\n    GREEN = 3\r\n\r\ntransitions = [['proceed', States.RED, States.YELLOW],\r\n               ['proceed', States.YELLOW, States.GREEN],\r\n               ['error', '*', States.ERROR]]\r\n\r\nm = Machine(states=States, transitions=transitions, initial=States.RED)\r\nassert m.is_RED()\r\nassert m.state is States.RED\r\nstate = m.get_state(States.RED)  # get transitions.State object\r\nprint(state.name)  # \u003e\u003e\u003e RED\r\nm.proceed()\r\nm.proceed()\r\nassert m.is_GREEN()\r\nm.error()\r\nassert m.state is States.ERROR\r\n```\r\n\r\nYou 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`).\r\nThus, it is not possible to have the states `'GREEN'` and `States.GREEN` at the same time.\r\n\r\n### \u003ca name=\"transitions\"\u003e\u003c/a\u003eTransitions\r\nSome of the above examples already illustrate the use of transitions in passing, but here we'll explore them in more detail.\r\n\r\nAs 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:\r\n\r\n```python\r\ntransitions = [\r\n    { 'trigger': 'melt', 'source': 'solid', 'dest': 'liquid' },\r\n    { 'trigger': 'evaporate', 'source': 'liquid', 'dest': 'gas' },\r\n    { 'trigger': 'sublimate', 'source': 'solid', 'dest': 'gas' },\r\n    { 'trigger': 'ionize', 'source': 'gas', 'dest': 'plasma' }\r\n]\r\nmachine = Machine(model=Matter(), states=states, transitions=transitions)\r\n```\r\n\r\nDefining 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.).\r\n\r\nThe following list-of-lists is functionally equivalent to the list-of-dictionaries above:\r\n\r\n```python\r\ntransitions = [\r\n    ['melt', 'solid', 'liquid'],\r\n    ['evaporate', 'liquid', 'gas'],\r\n    ['sublimate', 'solid', 'gas'],\r\n    ['ionize', 'gas', 'plasma']\r\n]\r\n```\r\n\r\nAlternatively, you can add transitions to a `Machine` after initialization:\r\n\r\n```python\r\nmachine = Machine(model=lump, states=states, initial='solid')\r\nmachine.add_transition('melt', source='solid', dest='liquid')\r\n```\r\n\r\nThe `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:\r\n\r\n```python\r\n\u003e\u003e\u003e lump.melt()\r\n\u003e\u003e\u003e lump.state\r\n'liquid'\r\n```\r\n\r\nBy default, calling an invalid trigger will raise an exception:\r\n\r\n```python\r\n\u003e\u003e\u003e lump.to_gas()\r\n\u003e\u003e\u003e # This won't work because only objects in a solid state can melt\r\n\u003e\u003e\u003e lump.melt()\r\ntransitions.core.MachineError: \"Can't trigger event melt from state gas!\"\r\n```\r\n\r\nThis 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):\r\n\r\n```python\r\n\u003e\u003e\u003e # Globally suppress invalid trigger exceptions\r\n\u003e\u003e\u003e m = Machine(lump, states, initial='solid', ignore_invalid_triggers=True)\r\n\u003e\u003e\u003e # ...or suppress for only one group of states\r\n\u003e\u003e\u003e states = ['new_state1', 'new_state2']\r\n\u003e\u003e\u003e m.add_states(states, ignore_invalid_triggers=True)\r\n\u003e\u003e\u003e # ...or even just for a single state. Here, exceptions will only be suppressed when the current state is A.\r\n\u003e\u003e\u003e states = [State('A', ignore_invalid_triggers=True), 'B', 'C']\r\n\u003e\u003e\u003e m = Machine(lump, states)\r\n\u003e\u003e\u003e # ...this can be inverted as well if just one state should raise an exception\r\n\u003e\u003e\u003e # since the machine's global value is not applied to a previously initialized state.\r\n\u003e\u003e\u003e states = ['A', 'B', State('C')] # the default value for 'ignore_invalid_triggers' is False\r\n\u003e\u003e\u003e m = Machine(lump, states, ignore_invalid_triggers=True)\r\n```\r\n\r\nIf you need to know which transitions are valid from a certain state, you can use `get_triggers`:\r\n\r\n```\r\nm.get_triggers('solid')\r\n\u003e\u003e\u003e ['melt', 'sublimate']\r\nm.get_triggers('liquid')\r\n\u003e\u003e\u003e ['evaporate']\r\nm.get_triggers('plasma')\r\n\u003e\u003e\u003e []\r\n# you can also query several states at once\r\nm.get_triggers('solid', 'liquid', 'gas', 'plasma')\r\n\u003e\u003e\u003e ['melt', 'evaporate', 'sublimate', 'ionize']\r\n```\r\n\r\n#### \u003ca name=\"automatic-transitions-for-all-states\"\u003e\u003c/a\u003eAutomatic transitions for all states\r\nIn 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:\r\n\r\n```python\r\nlump.to_liquid()\r\nlump.state\r\n\u003e\u003e\u003e 'liquid'\r\nlump.to_solid()\r\nlump.state\r\n\u003e\u003e\u003e 'solid'\r\n```\r\n\r\nIf you desire, you can disable this behavior by setting `auto_transitions=False` in the `Machine` initializer.\r\n\r\n#### \u003ca name=\"transitioning-from-multiple-states\"\u003e\u003c/a\u003eTransitioning from multiple states\r\nA given trigger can be attached to multiple transitions, some of which can potentially begin or end in the same state. For example:\r\n\r\n```python\r\nmachine.add_transition('transmogrify', ['solid', 'liquid', 'gas'], 'plasma')\r\nmachine.add_transition('transmogrify', 'plasma', 'solid')\r\n# This next transition will never execute\r\nmachine.add_transition('transmogrify', 'plasma', 'gas')\r\n```\r\n\r\nIn 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.)\r\n\r\nYou can also make a trigger cause a transition from _all_ states to a particular destination by using the `'*'` wildcard:\r\n\r\n```python\r\nmachine.add_transition('to_liquid', '*', 'liquid')\r\n```\r\n\r\nNote 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.\r\n\r\n#### \u003ca name=\"reflexive-from-multiple-states\"\u003e\u003c/a\u003eReflexive transitions from multiple states\r\nA reflexive trigger (trigger that has the same state as source and destination) can easily be added specifying `=` as destination.\r\nThis is handy if the same reflexive trigger should be added to multiple states.\r\nFor example:\r\n\r\n```python\r\nmachine.add_transition('touch', ['liquid', 'gas', 'plasma'], '=', after='change_shape')\r\n```\r\n\r\nThis will add reflexive transitions for all three states with `touch()` as trigger and with `change_shape` executed after each trigger.\r\n\r\n#### \u003ca name=\"internal-transitions\"\u003e\u003c/a\u003eInternal transitions\r\nIn contrast to reflexive transitions, internal transitions will never actually leave the state.\r\nThis means that transition-related callbacks such as `before` or `after` will be processed while state-related callbacks `exit` or `enter` will not.\r\nTo define a transition to be internal, set the destination to `None`.\r\n\r\n```python\r\nmachine.add_transition('internal', ['liquid', 'gas'], None, after='change_shape')\r\n```\r\n\r\n#### \u003ca name=\"ordered-transitions\"\u003e\u003c/a\u003e Ordered transitions\r\nA 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).\r\n\r\nTo facilitate this behavior, Transitions provides an `add_ordered_transitions()` method in the `Machine` class:\r\n\r\n```python\r\nstates = ['A', 'B', 'C']\r\n # See the \"alternative initialization\" section for an explanation of the 1st argument to init\r\nmachine = Machine(states=states, initial='A')\r\nmachine.add_ordered_transitions()\r\nmachine.next_state()\r\nprint(machine.state)\r\n\u003e\u003e\u003e 'B'\r\n# We can also define a different order of transitions\r\nmachine = Machine(states=states, initial='A')\r\nmachine.add_ordered_transitions(['A', 'C', 'B'])\r\nmachine.next_state()\r\nprint(machine.state)\r\n\u003e\u003e\u003e 'C'\r\n# Conditions can be passed to 'add_ordered_transitions' as well\r\n# If one condition is passed, it will be used for all transitions\r\nmachine = Machine(states=states, initial='A')\r\nmachine.add_ordered_transitions(conditions='check')\r\n# If a list is passed, it must contain exactly as many elements as the\r\n# machine contains states (A-\u003eB, ..., X-\u003eA)\r\nmachine = Machine(states=states, initial='A')\r\nmachine.add_ordered_transitions(conditions=['check_A2B', ..., 'check_X2A'])\r\n# Conditions are always applied starting from the initial state\r\nmachine = Machine(states=states, initial='B')\r\nmachine.add_ordered_transitions(conditions=['check_B2C', ..., 'check_A2B'])\r\n# With `loop=False`, the transition from the last state to the first state will be omitted (e.g. C-\u003eA)\r\n# When you also pass conditions, you need to pass one condition less (len(states)-1)\r\nmachine = Machine(states=states, initial='A')\r\nmachine.add_ordered_transitions(loop=False)\r\nmachine.next_state()\r\nmachine.next_state()\r\nmachine.next_state() # transitions.core.MachineError: \"Can't trigger event next_state from state C!\"\r\n```\r\n\r\n#### \u003ca name=\"queued-transitions\"\u003e\u003c/a\u003eQueued transitions\r\n\r\nThe 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.\r\n\r\n```python\r\ndef go_to_C():\r\n    global machine\r\n    machine.to_C()\r\n\r\ndef after_advance():\r\n    print(\"I am in state B now!\")\r\n\r\ndef entering_C():\r\n    print(\"I am in state C now!\")\r\n\r\nstates = ['A', 'B', 'C']\r\nmachine = Machine(states=states, initial='A')\r\n\r\n# we want a message when state transition to B has been completed\r\nmachine.add_transition('advance', 'A', 'B', after=after_advance)\r\n\r\n# call transition from state B to state C\r\nmachine.on_enter_B(go_to_C)\r\n\r\n# we also want a message when entering state C\r\nmachine.on_enter_C(entering_C)\r\nmachine.advance()\r\n\u003e\u003e\u003e 'I am in state C now!'\r\n\u003e\u003e\u003e 'I am in state B now!' # what?\r\n```\r\n\r\nThe execution order of this example is\r\n```\r\nprepare -\u003e before -\u003e on_enter_B -\u003e on_enter_C -\u003e after.\r\n```\r\nIf queued processing is enabled, a transition will be finished before the next transition is triggered:\r\n\r\n```python\r\nmachine = Machine(states=states, queued=True, initial='A')\r\n...\r\nmachine.advance()\r\n\u003e\u003e\u003e 'I am in state B now!'\r\n\u003e\u003e\u003e 'I am in state C now!' # That's better!\r\n```\r\n\r\nThis results in\r\n```\r\nprepare -\u003e before -\u003e on_enter_B -\u003e queue(to_C) -\u003e after  -\u003e on_enter_C.\r\n```\r\n**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.\r\n\r\n```python\r\nmachine.add_transition('jump', 'A', 'C', conditions='will_fail')\r\n...\r\n# queued=False\r\nmachine.jump()\r\n\u003e\u003e\u003e False\r\n# queued=True\r\nmachine.jump()\r\n\u003e\u003e\u003e True\r\n```\r\n\r\nWhen a model is removed from the machine, `transitions` will also remove all related events from the queue.\r\n\r\n```python\r\nclass Model:\r\n    def on_enter_B(self):\r\n        self.to_C()  # add event to queue ...\r\n        self.machine.remove_model(self)  # aaaand it's gone\r\n```\r\n\r\n\r\n#### \u003ca name=\"conditional-transitions\"\u003e\u003c/a\u003eConditional transitions\r\nSometimes 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:\r\n\r\n```python\r\n# Our Matter class, now with a bunch of methods that return booleans.\r\nclass Matter(object):\r\n    def is_flammable(self): return False\r\n    def is_really_hot(self): return True\r\n\r\nmachine.add_transition('heat', 'solid', 'gas', conditions='is_flammable')\r\nmachine.add_transition('heat', 'solid', 'liquid', conditions=['is_really_hot'])\r\n```\r\n\r\nIn 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`.\r\n\r\nFor convenience, there's also an `'unless'` argument that behaves exactly like conditions, but inverted:\r\n\r\n```python\r\nmachine.add_transition('heat', 'solid', 'gas', unless=['is_flammable', 'is_really_hot'])\r\n```\r\n\r\nIn this case, the model would transition from solid to gas whenever `heat()` fires, provided that both `is_flammable()` and `is_really_hot()` return `False`.\r\n\r\nNote that condition-checking methods will passively receive optional arguments and/or data objects passed to triggering methods. For instance, the following call:\r\n\r\n```python\r\nlump.heat(temp=74)\r\n# equivalent to lump.trigger('heat', temp=74)\r\n```\r\n\r\n... 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.\r\n\r\n#### \u003ca name=\"transition-callbacks\"\u003e\u003c/a\u003eCallbacks\r\nYou 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:\r\n\r\n```python\r\nclass Matter(object):\r\n    def make_hissing_noises(self): print(\"HISSSSSSSSSSSSSSSS\")\r\n    def disappear(self): print(\"where'd all the liquid go?\")\r\n\r\ntransitions = [\r\n    { 'trigger': 'melt', 'source': 'solid', 'dest': 'liquid', 'before': 'make_hissing_noises'},\r\n    { 'trigger': 'evaporate', 'source': 'liquid', 'dest': 'gas', 'after': 'disappear' }\r\n]\r\n\r\nlump = Matter()\r\nmachine = Machine(lump, states, transitions=transitions, initial='solid')\r\nlump.melt()\r\n\u003e\u003e\u003e \"HISSSSSSSSSSSSSSSS\"\r\nlump.evaporate()\r\n\u003e\u003e\u003e \"where'd all the liquid go?\"\r\n```\r\n\r\nThere is also a `'prepare'` callback that is executed as soon as a transition starts, before any `'conditions'` are checked or other callbacks are executed.\r\n\r\n```python\r\nclass Matter(object):\r\n    heat = False\r\n    attempts = 0\r\n    def count_attempts(self): self.attempts += 1\r\n    def heat_up(self): self.heat = random.random() \u003c 0.25\r\n    def stats(self): print('It took you %i attempts to melt the lump!' %self.attempts)\r\n\r\n    @property\r\n    def is_really_hot(self):\r\n        return self.heat\r\n    \r\n\r\nstates=['solid', 'liquid', 'gas', 'plasma']\r\n\r\ntransitions = [\r\n    { 'trigger': 'melt', 'source': 'solid', 'dest': 'liquid', 'prepare': ['heat_up', 'count_attempts'], 'conditions': 'is_really_hot', 'after': 'stats'},\r\n]\r\n\r\nlump = Matter()\r\nmachine = Machine(lump, states, transitions=transitions, initial='solid')\r\nlump.melt()\r\nlump.melt()\r\nlump.melt()\r\nlump.melt()\r\n\u003e\u003e\u003e \"It took you 4 attempts to melt the lump!\"\r\n```\r\n\r\nNote that `prepare` will not be called unless the current state is a valid source for the named transition.\r\n\r\nDefault actions meant to be executed before or after *every* transition can be passed to `Machine` during initialization with\r\n`before_state_change` and `after_state_change` respectively:\r\n\r\n```python\r\nclass Matter(object):\r\n    def make_hissing_noises(self): print(\"HISSSSSSSSSSSSSSSS\")\r\n    def disappear(self): print(\"where'd all the liquid go?\")\r\n\r\nstates=['solid', 'liquid', 'gas', 'plasma']\r\n\r\nlump = Matter()\r\nm = Machine(lump, states, before_state_change='make_hissing_noises', after_state_change='disappear')\r\nlump.to_gas()\r\n\u003e\u003e\u003e \"HISSSSSSSSSSSSSSSS\"\r\n\u003e\u003e\u003e \"where'd all the liquid go?\"\r\n```\r\n\r\nThere are also two keywords for callbacks which should be executed *independently* a) of how many transitions are possible,\r\nb) if any transition succeeds and c) even if an error is raised during the execution of some other callback.\r\nCallbacks passed to `Machine` with `prepare_event` will be executed *once* before processing possible transitions\r\n(and their individual `prepare` callbacks) takes place.\r\nCallbacks of `finalize_event` will be executed regardless of the success of the processed transitions.\r\nNote that if an error occurred it will be attached to `event_data` as `error` and can be retrieved with `send_event=True`.\r\n\r\n```python\r\nfrom transitions import Machine\r\n\r\nclass Matter(object):\r\n    def raise_error(self, event): raise ValueError(\"Oh no\")\r\n    def prepare(self, event): print(\"I am ready!\")\r\n    def finalize(self, event): print(\"Result: \", type(event.error), event.error)\r\n\r\nstates=['solid', 'liquid', 'gas', 'plasma']\r\n\r\nlump = Matter()\r\nm = Machine(lump, states, prepare_event='prepare', before_state_change='raise_error',\r\n            finalize_event='finalize', send_event=True)\r\ntry:\r\n    lump.to_gas()\r\nexcept ValueError:\r\n    pass\r\nprint(lump.state)\r\n\r\n# \u003e\u003e\u003e I am ready!\r\n# \u003e\u003e\u003e Result:  \u003cclass 'ValueError'\u003e Oh no\r\n# \u003e\u003e\u003e initial\r\n```\r\n\r\nSometimes things just don't work out as intended and we need to handle exceptions and clean up the mess to keep things going.\r\nWe can pass callbacks to `on_exception` to do this:\r\n\r\n```python\r\nfrom transitions import Machine\r\n\r\nclass Matter(object):\r\n    def raise_error(self, event): raise ValueError(\"Oh no\")\r\n    def handle_error(self, event):\r\n        print(\"Fixing things ...\")\r\n        del event.error  # it did not happen if we cannot see it ...\r\n\r\nstates=['solid', 'liquid', 'gas', 'plasma']\r\n\r\nlump = Matter()\r\nm = Machine(lump, states, before_state_change='raise_error', on_exception='handle_error', send_event=True)\r\ntry:\r\n    lump.to_gas()\r\nexcept ValueError:\r\n    pass\r\nprint(lump.state)\r\n\r\n# \u003e\u003e\u003e Fixing things ...\r\n# \u003e\u003e\u003e initial\r\n```\r\n\r\n\r\n### \u003ca name=\"resolution\"\u003e\u003c/a\u003eCallable resolution\r\n\r\nAs 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.\r\n\r\n```python\r\nfrom transitions import Machine\r\nfrom mod import imported_func\r\n\r\nimport random\r\n\r\n\r\nclass Model(object):\r\n\r\n    def a_callback(self):\r\n        imported_func()\r\n\r\n    @property\r\n    def a_property(self):\r\n        \"\"\" Basically a coin toss. \"\"\"\r\n        return random.random() \u003c 0.5\r\n\r\n    an_attribute = False\r\n\r\n\r\nmodel = Model()\r\nmachine = Machine(model=model, states=['A'], initial='A')\r\nmachine.add_transition('by_name', 'A', 'A', conditions='a_property', after='a_callback')\r\nmachine.add_transition('by_reference', 'A', 'A', unless=['a_property', 'an_attribute'], after=model.a_callback)\r\nmachine.add_transition('imported', 'A', 'A', after='mod.imported_func')\r\n\r\nmodel.by_name()\r\nmodel.by_reference()\r\nmodel.imported()\r\n```\r\n\r\nThe callable resolution is done in `Machine.resolve_callable`.\r\nThis method can be overridden in case more complex callable resolution strategies are required.\r\n\r\n\r\n**Example**\r\n```python\r\nclass CustomMachine(Machine):\r\n    @staticmethod\r\n    def resolve_callable(func, event_data):\r\n        # manipulate arguments here and return func, or super() if no manipulation is done.\r\n        super(CustomMachine, CustomMachine).resolve_callable(func, event_data)\r\n```\r\n\r\n### \u003ca name=\"execution-order\"\u003e\u003c/a\u003eCallback execution order\r\n\r\nIn summary, there are currently three ways to trigger events. You can call a model's convenience functions like `lump.melt()`,\r\nexecute triggers by name such as `lump.trigger(\"melt\")` or dispatch events on multiple models with `machine.dispatch(\"melt\")`\r\n(see section about multiple models in [alternative initialization patterns](#alternative-initialization-patterns)).\r\nCallbacks on transitions are then executed in the following order:\r\n\r\n|      Callback                  | Current State |               Comments                                      |\r\n|--------------------------------|:-------------:|-------------------------------------------------------------|\r\n| `'machine.prepare_event'`      | `source`      | executed *once* before individual transitions are processed |\r\n| `'transition.prepare'`         | `source`      | executed as soon as the transition starts                   |\r\n| `'transition.conditions'`      | `source`      | conditions *may* fail and halt the transition               |\r\n| `'transition.unless'`          | `source`      | conditions *may* fail and halt the transition               |\r\n| `'machine.before_state_change'`| `source`      | default callbacks declared on model                         |\r\n| `'transition.before'`          | `source`      |                                                             |\r\n| `'state.on_exit'`              | `source`      | callbacks declared on the source state                      |\r\n| `\u003cSTATE CHANGE\u003e`               |               |                                                             |\r\n| `'state.on_enter'`             | `destination` | callbacks declared on the destination state                 |\r\n| `'transition.after'`           | `destination` |                                                             |\r\n| `'machine.after_state_change'` | `destination` | default callbacks declared on model                         |\r\n| `'machine.on_exception'`       | `source/destination` | callbacks will be executed when an exception has been raised |\r\n| `'machine.finalize_event'`     | `source/destination` | callbacks will be executed even if no transition took place or an exception has been raised |\r\n\r\nIf 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. Note that each callback sequence has to be finished before the next stage is executed. Blocking callbacks will halt the execution order and therefore block the `trigger` or `dispatch` call itself. If you want callbacks to be executed in parallel, you could have a look at the [extensions](#extensions) `AsyncMachine` for asynchronous processing or `LockedMachine` for threading.\r\n\r\n### \u003ca name=\"passing-data\"\u003e\u003c/a\u003ePassing data\r\nSometimes you need to pass the callback functions registered at machine initialization some data that reflects the model's current state.\r\nTransitions allows you to do this in two different ways.\r\n\r\nFirst (the default), you can pass any positional or keyword arguments directly to the trigger methods (created when you call `add_transition()`):\r\n\r\n```python\r\nclass Matter(object):\r\n    def __init__(self): self.set_environment()\r\n    def set_environment(self, temp=0, pressure=101.325):\r\n        self.temp = temp\r\n        self.pressure = pressure\r\n    def print_temperature(self): print(\"Current temperature is %d degrees celsius.\" % self.temp)\r\n    def print_pressure(self): print(\"Current pressure is %.2f kPa.\" % self.pressure)\r\n\r\nlump = Matter()\r\nmachine = Machine(lump, ['solid', 'liquid'], initial='solid')\r\nmachine.add_transition('melt', 'solid', 'liquid', before='set_environment')\r\n\r\nlump.melt(45)  # positional arg;\r\n# equivalent to lump.trigger('melt', 45)\r\nlump.print_temperature()\r\n\u003e\u003e\u003e 'Current temperature is 45 degrees celsius.'\r\n\r\nmachine.set_state('solid')  # reset state so we can melt again\r\nlump.melt(pressure=300.23)  # keyword args also work\r\nlump.print_pressure()\r\n\u003e\u003e\u003e 'Current pressure is 300.23 kPa.'\r\n\r\n```\r\n\r\nYou can pass any number of arguments you like to the trigger.\r\n\r\nThere 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.\r\n\r\nTo 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.)\r\n\r\n```python\r\nclass Matter(object):\r\n\r\n    def __init__(self):\r\n        self.temp = 0\r\n        self.pressure = 101.325\r\n\r\n    # Note that the sole argument is now the EventData instance.\r\n    # This object stores positional arguments passed to the trigger method in the\r\n    # .args property, and stores keywords arguments in the .kwargs dictionary.\r\n    def set_environment(self, event):\r\n        self.temp = event.kwargs.get('temp', 0)\r\n        self.pressure = event.kwargs.get('pressure', 101.325)\r\n\r\n    def print_pressure(self): print(\"Current pressure is %.2f kPa.\" % self.pressure)\r\n\r\nlump = Matter()\r\nmachine = Machine(lump, ['solid', 'liquid'], send_event=True, initial='solid')\r\nmachine.add_transition('melt', 'solid', 'liquid', before='set_environment')\r\n\r\nlump.melt(temp=45, pressure=1853.68)  # keyword args\r\nlump.print_pressure()\r\n\u003e\u003e\u003e 'Current pressure is 1853.68 kPa.'\r\n\r\n```\r\n\r\n### \u003ca name=\"alternative-initialization-patterns\"\u003e\u003c/a\u003eAlternative initialization patterns\r\n\r\nIn 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()`).\r\n\r\nFortunately, Transitions is flexible, and supports two other initialization patterns.\r\n\r\nFirst, you can create a standalone state machine that doesn't require another model at all. Simply omit the model argument during initialization:\r\n\r\n```python\r\nmachine = Machine(states=states, transitions=transitions, initial='solid')\r\nmachine.melt()\r\nmachine.state\r\n\u003e\u003e\u003e 'liquid'\r\n```\r\n\r\nIf 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.\r\n\r\nThis 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.\r\n\r\nAn 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!):\r\n\r\n```python\r\nclass Matter(Machine):\r\n    def say_hello(self): print(\"hello, new state!\")\r\n    def say_goodbye(self): print(\"goodbye, old state!\")\r\n\r\n    def __init__(self):\r\n        states = ['solid', 'liquid', 'gas']\r\n        Machine.__init__(self, states=states, initial='solid')\r\n        self.add_transition('melt', 'solid', 'liquid')\r\n\r\nlump = Matter()\r\nlump.state\r\n\u003e\u003e\u003e 'solid'\r\nlump.melt()\r\nlump.state\r\n\u003e\u003e\u003e 'liquid'\r\n```\r\n\r\nHere 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.\r\n\r\nA machine can handle multiple models which can be passed as a list like `Machine(model=[model1, model2, ...])`.\r\nIn 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, ...])`.\r\nYou can also create a standalone machine, and register models dynamically via `machine.add_model` by passing `model=None` to the constructor.\r\nFurthermore, you can use `machine.dispatch` to trigger events on all currently added models.\r\nRemember to call `machine.remove_model` if machine is long-lasting and your models are temporary and should be garbage collected:\r\n\r\n```python\r\nclass Matter():\r\n    pass\r\n\r\nlump1 = Matter()\r\nlump2 = Matter()\r\n\r\n# setting 'model' to None or passing an empty list will initialize the machine without a model\r\nmachine = Machine(model=None, states=states, transitions=transitions, initial='solid')\r\n\r\nmachine.add_model(lump1)\r\nmachine.add_model(lump2, initial='liquid')\r\n\r\nlump1.state\r\n\u003e\u003e\u003e 'solid'\r\nlump2.state\r\n\u003e\u003e\u003e 'liquid'\r\n\r\n# custom events as well as auto transitions can be dispatched to all models\r\nmachine.dispatch(\"to_plasma\")\r\n\r\nlump1.state\r\n\u003e\u003e\u003e 'plasma'\r\nassert lump1.state == lump2.state\r\n\r\nmachine.remove_model([lump1, lump2])\r\ndel lump1  # lump1 is garbage collected\r\ndel lump2  # lump2 is garbage collected\r\n```\r\n\r\nIf you don't provide an initial state in the state machine constructor, `transitions` will create and add a default state called `'initial'`.\r\nIf you do not want a default initial state, you can pass `initial=None`.\r\nHowever, in this case you need to pass an initial state every time you add a model. \r\n\r\n```python\r\nmachine = Machine(model=None, states=states, transitions=transitions, initial=None)\r\n\r\nmachine.add_model(Matter())\r\n\u003e\u003e\u003e \"MachineError: No initial state configured for machine, must specify when adding model.\"\r\nmachine.add_model(Matter(), initial='liquid')\r\n```\r\n\r\nModels with multiple states could attach multiple machines using different `model_attribute` values. As mentioned in [Checking state](#checking-state), this will add custom `is/to_\u003cmodel_attribute\u003e_\u003cstate_name\u003e` functions: \r\n\r\n```python\r\nlump = Matter()\r\n\r\nmatter_machine = Machine(lump, states=['solid', 'liquid', 'gas'], initial='solid')\r\n# add a second machine to the same model but assign a different state attribute\r\nshipment_machine = Machine(lump, states=['delivered', 'shipping'], initial='delivered', model_attribute='shipping_state')\r\n\r\nlump.state\r\n\u003e\u003e\u003e 'solid'\r\nlump.is_solid()  # check the default field\r\n\u003e\u003e\u003e True\r\nlump.shipping_state\r\n\u003e\u003e\u003e 'delivered'\r\nlump.is_shipping_state_delivered()  # check the custom field.\r\n\u003e\u003e\u003e True\r\nlump.to_shipping_state_shipping()\r\n\u003e\u003e\u003e True\r\nlump.is_shipping_state_delivered()\r\n\u003e\u003e\u003e False\r\n```\r\n\r\n### Logging\r\n\r\nTransitions 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:\r\n\r\n```python\r\n# Set up logging; The basic log level will be DEBUG\r\nimport logging\r\nlogging.basicConfig(level=logging.DEBUG)\r\n# Set transitions' log level to INFO; DEBUG messages will be omitted\r\nlogging.getLogger('transitions').setLevel(logging.INFO)\r\n\r\n# Business as usual\r\nmachine = Machine(states=states, transitions=transitions, initial='solid')\r\n...\r\n```\r\n\r\n### \u003ca name=\"restoring\"\u003e\u003c/a\u003e(Re-)Storing machine instances\r\n\r\nMachines are picklable and can be stored and loaded with `pickle`. For Python 3.3 and earlier `dill` is required.\r\n\r\n```python\r\nimport dill as pickle # only required for Python 3.3 and earlier\r\n\r\nm = Machine(states=['A', 'B', 'C'], initial='A')\r\nm.to_B()\r\nm.state  \r\n\u003e\u003e\u003e B\r\n\r\n# store the machine\r\ndump = pickle.dumps(m)\r\n\r\n# load the Machine instance again\r\nm2 = pickle.loads(dump)\r\n\r\nm2.state\r\n\u003e\u003e\u003e B\r\n\r\nm2.states.keys()\r\n\u003e\u003e\u003e ['A', 'B', 'C']\r\n```\r\n\r\n### \u003ca name=\"extensions\"\u003e\u003c/a\u003e Extensions\r\n\r\nEven though the core of transitions is kept lightweight, there are a variety of MixIns to extend its functionality. Currently supported are:\r\n\r\n- **Diagrams** to visualize the current state of a machine\r\n- **Hierarchical State Machines** for nesting and reuse\r\n- **Threadsafe Locks** for parallel execution\r\n- **Async callbacks** for asynchronous execution\r\n- **Custom States** for extended state-related behaviour\r\n\r\nThere are two mechanisms to retrieve a state machine instance with the desired features enabled.\r\nThe 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:\r\n\r\n```python\r\nfrom transitions.extensions import MachineFactory\r\n\r\n# create a machine with mixins\r\ndiagram_cls = MachineFactory.get_predefined(graph=True)\r\nnested_locked_cls = MachineFactory.get_predefined(nested=True, locked=True)\r\nasync_machine_cls = MachineFactory.get_predefined(asyncio=True)\r\n\r\n# create instances from these classes\r\n# instances can be used like simple machines\r\nmachine1 = diagram_cls(model, state, transitions)\r\nmachine2 = nested_locked_cls(model, state, transitions)\r\n```\r\n\r\nThis approach targets experimental use since in this case the underlying classes do not have to be known.\r\nHowever, classes can also be directly imported from `transitions.extensions`. The naming scheme is as follows:\r\n\r\n|                                | Diagrams | Nested | Locked | Asyncio |\r\n| -----------------------------: | :------: | :----: | :----: | :---: |\r\n| Machine                        | ✘        | ✘      | ✘      | ✘ |\r\n| GraphMachine                   | ✓        | ✘      | ✘      | ✘ |\r\n| HierarchicalMachine            | ✘        | ✓      | ✘      | ✘ |\r\n| LockedMachine                  | ✘        | ✘      | ✓      | ✘ |\r\n| HierarchicalGraphMachine       | ✓        | ✓      | ✘      | ✘ |\r\n| LockedGraphMachine             | ✓        | ✘      | ✓      | ✘ |\r\n| LockedHierarchicalMachine      | ✘        | ✓      | ✓      | ✘ |\r\n| LockedHierarchicalGraphMachine | ✓        | ✓      | ✓      | ✘ |\r\n| AsyncMachine                   | ✘        | ✘      | ✘      | ✓ |\r\n| AsyncGraphMachine              | ✓        | ✘      | ✘      | ✓ |\r\n| HierarchicalAsyncMachine       | ✘        | ✓      | ✘      | ✓ |\r\n| HierarchicalAsyncGraphMachine  | ✓        | ✓      | ✘      | ✓ |\r\n\r\nTo use a feature-rich state machine, one could write:\r\n\r\n```python\r\nfrom transitions.extensions import LockedHierarchicalGraphMachine as LHGMachine\r\n\r\nmachine = LHGMachine(model, states, transitions)\r\n```\r\n\r\n#### \u003ca name=\"diagrams\"\u003e\u003c/a\u003e Diagrams\r\n\r\nAdditional Keywords:\r\n* `title` (optional): Sets the title of the generated image.\r\n* `show_conditions` (default False): Shows conditions at transition edges\r\n* `show_auto_transitions` (default False): Shows auto transitions in graph\r\n* `show_state_attributes` (default False): Show callbacks (enter, exit), tags and timeouts in graph\r\n\r\nTransitions 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:   \r\nTo generate graphs with the package `graphviz`, you need to install [Graphviz](https://graphviz.org/) manually or via a package manager.\r\n\r\n    sudo apt-get install graphviz graphviz-dev  # Ubuntu and Debian\r\n    brew install graphviz  # MacOS\r\n    conda install graphviz python-graphviz  # (Ana)conda\r\n\r\nNow you can install the actual Python packages\r\n\r\n    pip install graphviz pygraphviz # install graphviz and/or pygraphviz manually...\r\n    pip install transitions[diagrams]  # ... or install transitions with 'diagrams' extras which currently depends on pygraphviz\r\n\r\nCurrently, `GraphMachine` will use `pygraphviz` when available and fall back to `graphviz` when `pygraphviz` cannot be \r\nfound. This can be overridden by passing `use_pygraphviz=False` to the constructor. Note that this default might change \r\nin the future and `pygraphviz` support may be dropped.\r\nWith `Model.get_graph()` you can get the current graph or the region of interest (roi) and draw it like this:\r\n\r\n```python\r\n# import transitions\r\n\r\nfrom transitions.extensions import GraphMachine\r\nm = Model()\r\n# without further arguments pygraphviz will be used\r\nmachine = GraphMachine(model=m, ...)\r\n# when you want to use graphviz explicitly\r\nmachine = GraphMachine(model=m, use_pygraphviz=False, ...)\r\n# in cases where auto transitions should be visible\r\nmachine = GraphMachine(model=m, show_auto_transitions=True, ...)\r\n\r\n# draw the whole graph ...\r\nm.get_graph().draw('my_state_diagram.png', prog='dot')\r\n# ... or just the region of interest\r\n# (previous state, active state and all reachable states)\r\nroi = m.get_graph(show_roi=True).draw('my_state_diagram.png', prog='dot')\r\n```\r\n\r\nThis produces something like this:\r\n\r\n![state diagram example](https://user-images.githubusercontent.com/205986/47524268-725c1280-d89a-11e8-812b-1d3b6e667b91.png)\r\n\r\nIndependent of the backend you use, the draw function also accepts a file descriptor or a binary stream as the first argument. If you set this parameter to `None`, the byte stream will be returned:\r\n\r\n```python\r\nimport io\r\n\r\nwith open('a_graph.png', 'bw') as f:\r\n    # you need to pass the format when you pass objects instead of filenames.\r\n    m.get_graph().draw(f, format=\"png\", prog='dot')\r\n\r\n# you can pass a (binary) stream too\r\nb = io.BytesIO()\r\nm.get_graph().draw(b, format=\"png\", prog='dot')\r\n\r\n# or just handle the binary string yourself\r\nresult = m.get_graph().draw(None, format=\"png\", prog='dot')\r\nassert result == b.getvalue()\r\n```\r\n\r\nReferences and partials passed as callbacks will be resolved as good as possible:\r\n\r\n```python\r\nfrom transitions.extensions import GraphMachine\r\nfrom functools import partial\r\n\r\n\r\nclass Model:\r\n\r\n    def clear_state(self, deep=False, force=False):\r\n        print(\"Clearing state ...\")\r\n        return True\r\n\r\n\r\nmodel = Model()\r\nmachine = GraphMachine(model=model, states=['A', 'B', 'C'],\r\n                       transitions=[\r\n                           {'trigger': 'clear', 'source': 'B', 'dest': 'A', 'conditions': model.clear_state},\r\n                           {'trigger': 'clear', 'source': 'C', 'dest': 'A',\r\n                            'conditions': partial(model.clear_state, False, force=True)},\r\n                       ],\r\n                       initial='A', show_conditions=True)\r\n\r\nmodel.get_graph().draw('my_state_diagram.png', prog='dot')\r\n```\r\n\r\nThis should produce something similar to this:\r\n\r\n![state diagram references_example](https://user-images.githubusercontent.com/205986/110783076-39087f80-8268-11eb-8fa1-fc7bac97f4cf.png)\r\n\r\nIf the format of references does not suit your needs, you can override the static method `GraphMachine.format_references`. If you want to skip reference entirely, just let `GraphMachine.format_references` return `None`.\r\nAlso, have a look at our [example](./examples) IPython/Jupyter notebooks for a more detailed example about how to use and edit graphs.\r\n\r\n\r\n### \u003ca name=\"hsm\"\u003e\u003c/a\u003eHierarchical State Machine (HSM)\r\n\r\nTransitions includes an extension module which allows to nest states.\r\nThis allows to create contexts and to model cases where states are related to certain subtasks in the state machine.\r\nTo create a nested state, either import `NestedState` from transitions or use a dictionary with the initialization arguments `name` and `children`.\r\nOptionally, `initial` can be used to define a sub state to transit to, when the nested state is entered.\r\n\r\n```python\r\nfrom transitions.extensions import HierarchicalMachine\r\n\r\nstates = ['standing', 'walking', {'name': 'caffeinated', 'children':['dithering', 'running']}]\r\ntransitions = [\r\n  ['walk', 'standing', 'walking'],\r\n  ['stop', 'walking', 'standing'],\r\n  ['drink', '*', 'caffeinated'],\r\n  ['walk', ['caffeinated', 'caffeinated_dithering'], 'caffeinated_running'],\r\n  ['relax', 'caffeinated', 'standing']\r\n]\r\n\r\nmachine = HierarchicalMachine(states=states, transitions=transitions, initial='standing', ignore_invalid_triggers=True)\r\n\r\nmachine.walk() # Walking now\r\nmachine.stop() # let's stop for a moment\r\nmachine.drink() # coffee time\r\nmachine.state\r\n\u003e\u003e\u003e 'caffeinated'\r\nmachine.walk() # we have to go faster\r\nmachine.state\r\n\u003e\u003e\u003e 'caffeinated_running'\r\nmachine.stop() # can't stop moving!\r\nmachine.state\r\n\u003e\u003e\u003e 'caffeinated_running'\r\nmachine.relax() # leave nested state\r\nmachine.state # phew, what a ride\r\n\u003e\u003e\u003e 'standing'\r\n# machine.on_enter_caffeinated_running('callback_method')\r\n```\r\n\r\nA configuration making use of  `initial` could look like this:\r\n\r\n```python\r\n# ...\r\nstates = ['standing', 'walking', {'name': 'caffeinated', 'initial': 'dithering', 'children': ['dithering', 'running']}]\r\ntransitions = [\r\n  ['walk', 'standing', 'walking'],\r\n  ['stop', 'walking', 'standing'],\r\n  # this transition will end in 'caffeinated_dithering'...\r\n  ['drink', '*', 'caffeinated'],\r\n  # ... that is why we do not need do specify 'caffeinated' here anymore\r\n  ['walk', 'caffeinated_dithering', 'caffeinated_running'],\r\n  ['relax', 'caffeinated', 'standing']\r\n]\r\n# ...\r\n```\r\nThe `initial` keyword of the `HierarchicalMachine` constructor accepts nested states (e.g. `initial='caffeinated_running'`) and a list of states which is considered to be a parallel state (e.g. `initial=['A', 'B']`) or the current state of another model (`initial=model.state`) which should be effectively one of the previous mentioned options. Note that when passing a string, `transition` will check the targeted state for `initial` substates and use this as an entry state. This will be done recursively until a substate does not mention an initial state. Parallel states or a state passed as a list will be used 'as is' and no further initial evaluation will be conducted. \r\n\r\nNote that your previously created state object *must be* a `NestedState` or a derived class of it.\r\nThe standard `State` class used in simple `Machine` instances lacks features required for nesting.\r\n\r\n```python\r\nfrom transitions.extensions.nesting import HierarchicalMachine, NestedState\r\nfrom transitions import  State\r\nm = HierarchicalMachine(states=['A'], initial='initial')\r\nm.add_state('B')  # fine\r\nm.add_state({'name': 'C'})  # also fine\r\nm.add_state(NestedState('D'))  # fine as well\r\nm.add_state(State('E'))  # does not work!\r\n```\r\n\r\nSome things that have to be considered when working with nested states: State *names are concatenated* with `NestedState.separator`.\r\nCurrently the separator is set to underscore ('_') and therefore behaves similar to the basic machine.\r\nThis 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.\r\nWhen entering a substate, `enter` will be called for all parent states. The same is true for exiting substates.\r\nThird, nested states can overwrite transition behaviour of their parents.\r\nIf a transition is not known to the current state it will be delegated to its parent.\r\n\r\n**This means that in the standard configuration, state names in HSMs MUST NOT contain underscores.**\r\nFor `transitions` it's impossible to tell whether `machine.add_state('state_name')` should add a state named `state_name` or add a substate `name` to the state `state`.\r\nIn some cases this is not sufficient however.\r\nFor instance if state names consists of more than one word and you want/need to use underscore to separate them instead of `CamelCase`.\r\nTo deal with this, you can change the character used for separation quite easily.\r\nYou can even use fancy unicode characters if you use Python 3.\r\nSetting the separator to something else than underscore changes some of the behaviour (auto_transition and setting callbacks) though:\r\n\r\n```python\r\nfrom transitions.extensions import HierarchicalMachine\r\nfrom transitions.extensions.nesting import NestedState\r\nNestedState.separator = '↦'\r\nstates = ['A', 'B',\r\n  {'name': 'C', 'children':['1', '2',\r\n    {'name': '3', 'children': ['a', 'b', 'c']}\r\n  ]}\r\n]\r\n\r\ntransitions = [\r\n    ['reset', 'C', 'A'],\r\n    ['reset', 'C↦2', 'C']  # overwriting parent reset\r\n]\r\n\r\n# we rely on auto transitions\r\nmachine = HierarchicalMachine(states=states, transitions=transitions, initial='A')\r\nmachine.to_B()  # exit state A, enter state B\r\nmachine.to_C()  # exit B, enter C\r\nmachine.to_C.s3.a()  # enter C↦a; enter C↦3↦a;\r\nmachine.state\r\n\u003e\u003e\u003e 'C↦3↦a'\r\nassert machine.is_C.s3.a()\r\nmachine.to('C↦2')  # not interactive; exit C↦3↦a, exit C↦3, enter C↦2\r\nmachine.reset()  # exit C↦2; reset C has been overwritten by C↦3\r\nmachine.state\r\n\u003e\u003e\u003e 'C'\r\nmachine.reset()  # exit C, enter A\r\nmachine.state\r\n\u003e\u003e\u003e 'A'\r\n# s.on_enter('C↦3↦a', 'callback_method')\r\n```\r\n\r\nInstead 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.\r\nIf interactive completion is not required, `to('C↦3↦a')` can be called directly. Additionally, `on_enter/exit_\u003c\u003cstate name\u003e\u003e` is replaced with `on_enter/exit(state_name, callback)`. State checks can be conducted in a similar fashion. Instead of `is_C_3_a()`, the `FunctionWrapper` variant `is_C.s3.a()` can be used.\r\n\r\nTo check whether the current state is a substate of a specific state, `is_state` supports the keyword `allow_substates`:\r\n\r\n```python\r\nmachine.state\r\n\u003e\u003e\u003e 'C.2.a'\r\nmachine.is_C() # checks for specific states\r\n\u003e\u003e\u003e False\r\nmachine.is_C(allow_substates=True)\r\n\u003e\u003e\u003e True\r\nassert machine.is_C.s2() is False\r\nassert machine.is_C.s2(allow_substates=True)  # FunctionWrapper support allow_substate as well\r\n```\r\n\r\n*new in 0.8.0*  \r\nYou can use enumerations in HSMs as well but keep in mind that `Enum` are compared by value.\r\nIf you have a value more than once in a state tree those states cannot be distinguished.\r\n\r\n```python\r\nstates = [States.RED, States.YELLOW, {'name': States.GREEN, 'children': ['tick', 'tock']}]\r\nstates = ['A', {'name': 'B', 'children': states, 'initial': States.GREEN}, States.GREEN]\r\nmachine = HierarchicalMachine(states=states)\r\nmachine.to_B()\r\nmachine.is_GREEN()  # returns True even though the actual state is B_GREEN\r\n```\r\n\r\n*new in 0.8.0*  \r\n`HierarchicalMachine` has been rewritten from scratch to support parallel states and better isolation of nested states.\r\nThis involves some tweaks based on community feedback.\r\nTo get an idea of processing order and configuration have a look at the following example:\r\n\r\n```python\r\nfrom transitions.extensions.nesting import HierarchicalMachine\r\nimport logging\r\nstates = ['A', 'B', {'name': 'C', 'parallel': [{'name': '1', 'children': ['a', 'b', 'c'], 'initial': 'a',\r\n                                                'transitions': [['go', 'a', 'b']]},\r\n                                               {'name': '2', 'children': ['x', 'y', 'z'], 'initial': 'z'}],\r\n                      'transitions': [['go', '2_z', '2_x']]}]\r\n\r\ntransitions = [['reset', 'C_1_b', 'B']]\r\nlogging.basicConfig(level=logging.INFO)\r\nmachine = HierarchicalMachine(states=states, transitions=transitions, initial='A')\r\nmachine.to_C()\r\n# INFO:transitions.extensions.nesting:Exited state A\r\n# INFO:transitions.extensions.nesting:Entered state C\r\n# INFO:transitions.extensions.nesting:Entered state C_1\r\n# INFO:transitions.extensions.nesting:Entered state C_2\r\n# INFO:transitions.extensions.nesting:Entered state C_1_a\r\n# INFO:transitions.extensions.nesting:Entered state C_2_z\r\nmachine.go()\r\n# INFO:transitions.extensions.nesting:Exited state C_1_a\r\n# INFO:transitions.extensions.nesting:Entered state C_1_b\r\n# INFO:transitions.extensions.nesting:Exited state C_2_z\r\n# INFO:transitions.extensions.nesting:Entered state C_2_x\r\nmachine.reset()\r\n# INFO:transitions.extensions.nesting:Exited state C_1_b\r\n# INFO:transitions.extensions.nesting:Exited state C_2_x\r\n# INFO:transitions.extensions.nesting:Exited state C_1\r\n# INFO:transitions.extensions.nesting:Exited state C_2\r\n# INFO:transitions.extensions.nesting:Exited state C\r\n# INFO:transitions.extensions.nesting:Entered state B\r\n```\r\n\r\nWhen using `parallel` instead of `children`, `transitions` will enter all states of the passed list at the same time.\r\nWhich substate to enter is defined by `initial` which should *always* point to a direct substate.\r\nA novel feature is to define local transitions by passing the `transitions` keyword in a state definition.\r\nThe above defined transition `['go', 'a', 'b']` is only valid in `C_1`.\r\nWhile you can reference substates as done in `['go', '2_z', '2_x']` you cannot reference parent states directly in locally defined transitions.\r\nWhen a parent state is exited, its children will also be exited.\r\nIn 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.\r\nTransitions 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`)\r\nStarting with *0.8.0* nested states can be added directly and will issue the creation of parent states on-the-fly:\r\n\r\n```python\r\nm = HierarchicalMachine(states=['A'], initial='A')\r\nm.add_state('B_1_a')\r\nm.to_B_1()\r\nassert m.is_B(allow_substates=True)\r\n```\r\n\r\n\r\n#### Reuse of previously created HSMs\r\n\r\nBesides semantic order, nested states are very handy if you want to specify state machines for specific tasks and plan to reuse them.\r\nBefore *0.8.0*, a `HierarchicalMachine` would not integrate the machine instance itself but the states and transitions by creating copies of them.\r\nHowever, since *0.8.0* `(Nested)State` instances are just **referenced** which means changes in one machine's collection of states and events will influence the other machine instance. Models and their state will not be shared though.\r\nNote that events and transitions are also copied by reference and will be shared by both instances if you do not use the `remap` keyword.\r\nThis change was done to be more in line with `Machine` which also uses passed `State` instances by reference.\r\n\r\n```python\r\ncount_states = ['1', '2', '3', 'done']\r\ncount_trans = [\r\n    ['increase', '1', '2'],\r\n    ['increase', '2', '3'],\r\n    ['decrease', '3', '2'],\r\n    ['decrease', '2', '1'],\r\n    ['done', '3', 'done'],\r\n    ['reset', '*', '1']\r\n]\r\n\r\ncounter = HierarchicalMachine(states=count_states, transitions=count_trans, initial='1')\r\n\r\ncounter.increase() # love my counter\r\nstates = ['waiting', 'collecting', {'name': 'counting', 'children': counter}]\r\n\r\ntransitions = [\r\n    ['collect', '*', 'collecting'],\r\n    ['wait', '*', 'waiting'],\r\n    ['count', 'collecting', 'counting']\r\n]\r\n\r\ncollector = HierarchicalMachine(states=states, transitions=transitions, initial='waiting')\r\ncollector.collect()  # collecting\r\ncollector.count()  # let's see what we got; counting_1\r\ncollector.increase()  # counting_2\r\ncollector.increase()  # counting_3\r\ncollector.done()  # collector.state == counting_done\r\ncollector.wait()  # collector.state == waiting\r\n```\r\n\r\nIf a `HierarchicalMachine` is passed with the `children` keyword, the initial state of this machine will be assigned to the new parent state.\r\nIn the above example we see that entering `counting` will also enter `counting_1`.\r\nIf 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}`.\r\n\r\nSometimes 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.\r\nTo achieve this behaviour you can remap state transitions.\r\nIn the example above we would like the counter to return if the state `done` was reached.\r\nThis is done as follows:\r\n\r\n```python\r\nstates = ['waiting', 'collecting', {'name': 'counting', 'children': counter, 'remap': {'done': 'waiting'}}]\r\n\r\n... # same as above\r\n\r\ncollector.increase() # counting_3\r\ncollector.done()\r\ncollector.state\r\n\u003e\u003e\u003e 'waiting' # be aware that 'counting_done' will be removed from the state machine\r\n```\r\n\r\nAs mentioned above, using `remap` will **copy** events and transitions since they could not be valid in the original state machine.\r\nIf a reused state machine does not have a final state, you can of course add the transitions manually.\r\nIf 'counter' had no 'done' state, we could just add `['done', 'counter_3', 'waiting']` to achieve the same behaviour.\r\n\r\nIn cases where you want states and transitions to be copied by value rather than reference (for instance, if you want to keep the pre-0.8 behaviour) you can do so by creating a `NestedState` and assign deep copies of the machine's events and states to it.\r\n\r\n```python\r\nfrom transitions.extensions.nesting import NestedState\r\nfrom copy import deepcopy\r\n\r\n# ... configuring and creating counter \r\n\r\ncounting_state = NestedState(name=\"counting\", initial='1')\r\ncounting_state.states = deepcopy(counter.states)\r\ncounting_state.events = deepcopy(counter.events)\r\n\r\nstates = ['waiting', 'collecting', counting_state]\r\n```\r\n\r\nFor complex state machines, sharing configurations rather than instantiated machines might be more feasible.\r\nEspecially since instantiated machines must be derived from `HierarchicalMachine`.\r\nSuch configurations can be stored and loaded easily via JSON or YAML (see the [FAQ](examples/Frequently%20asked%20questions.ipynb)).\r\n`HierarchicalMachine` allows defining substates either with the keyword `children` or `states`.\r\nIf both are present, only `children` will be considered.\r\n\r\n```python\r\ncounter_conf = {\r\n    'name': 'counting',\r\n    'states': ['1', '2', '3', 'done'],\r\n    'transitions': [\r\n        ['increase', '1', '2'],\r\n        ['increase', '2', '3'],\r\n        ['decrease', '3', '2'],\r\n        ['decrease', '2', '1'],\r\n        ['done', '3', 'done'],\r\n        ['reset', '*', '1']\r\n    ],\r\n    'initial': '1'\r\n}\r\n\r\ncollector_conf = {\r\n    'name': 'collector',\r\n    'states': ['waiting', 'collecting', counter_conf],\r\n    'transitions': [\r\n        ['collect', '*', 'collecting'],\r\n        ['wait', '*', 'waiting'],\r\n        ['count', 'collecting', 'counting']\r\n    ],\r\n    'initial': 'waiting'\r\n}\r\n\r\ncollector = HierarchicalMachine(**collector_conf)\r\ncollector.collect()\r\ncollector.count()\r\ncollector.increase()\r\nassert collector.is_counting_2()\r\n```\r\n\r\n#### \u003ca name=\"threading\"\u003e\u003c/a\u003e Threadsafe(-ish) State Machine\r\n\r\nIn cases where event dispatching is done in threads, one can use either `LockedMachine` or `LockedHierarchicalMachine` where **function access** (!sic) is secured with reentrant locks.\r\nThis does not save you from corrupting your machine by tinkering with member variables of your model or state machine.\r\n\r\n```python\r\nfrom transitions.extensions import LockedMachine\r\nfrom threading import Thread\r\nimport time\r\n\r\nstates = ['A', 'B', 'C']\r\nmachine = LockedMachine(states=states, initial='A')\r\n\r\n# let us assume that entering B will take some time\r\nthread = Thread(target=machine.to_B)\r\nthread.start()\r\ntime.sleep(0.01) # thread requires some time to start\r\nmachine.to_C() # synchronized access; won't execute before thread is done\r\n# accessing attributes directly\r\nthread = Thread(target=machine.to_B)\r\nthread.start()\r\nmachine.new_attrib = 42 # not synchronized! will mess with execution order\r\n```\r\n\r\nAny python context manager can be passed in via the `machine_context` keyword argument:\r\n\r\n```python\r\nfrom transitions.extensions import LockedMachine\r\nfrom threading import RLock\r\n\r\nstates = ['A', 'B', 'C']\r\n\r\nlock1 = RLock()\r\nlock2 = RLock()\r\n\r\nmachine = LockedMachine(states=states, initial='A', machine_context=[lock1, lock2])\r\n```\r\n\r\nAny contexts via `machine_model` will be shared between all models registered with the `Machine`.\r\nPer-model contexts can be added as well:\r\n\r\n```python\r\nlock3 = RLock()\r\n\r\nmachine.add_model(model, model_context=lock3)\r\n```\r\n\r\nIt's important that all user-provided context managers are re-entrant since the state machine will call them multiple\r\ntimes, even in the context of a single trigger invocation.\r\n\r\n\r\n#### \u003ca name=\"async\"\u003e\u003c/a\u003e Using async callbacks\r\n\r\nIf you are using Python 3.7 or later, you can use `AsyncMachine` to work with asynchronous callbacks.\r\nYou can mix synchronous and asynchronous callbacks if you like but this may have undesired side effects.\r\nNote that events need to be awaited and the event loop must also be handled by you.\r\n\r\n```python\r\nfrom transitions.extensions.asyncio import AsyncMachine\r\nimport asyncio\r\nimport time\r\n\r\n\r\nclass AsyncModel:\r\n\r\n    def prepare_model(self):\r\n        print(\"I am synchronous.\")\r\n        self.start_time = time.time()\r\n\r\n    async def before_change(self):\r\n        print(\"I am asynchronous and will block now for 100 milliseconds.\")\r\n        await asyncio.sleep(0.1)\r\n        print(\"I am done waiting.\")\r\n\r\n    def sync_before_change(self):\r\n        print(\"I am synchronous and will block the event loop (what I probably shouldn't)\")\r\n        time.sleep(0.1)\r\n        print(\"I am done waiting synchronously.\")\r\n\r\n    def after_change(self):\r\n        print(f\"I am synchronous again. Execution took {int((time.time() - self.start_time) * 1000)} ms.\")\r\n\r\n\r\ntransition = dict(trigger=\"start\", source=\"Start\", dest=\"Done\", prepare=\"prepare_model\",\r\n                  before=[\"before_change\"] * 5 + [\"sync_before_change\"],\r\n                  after=\"after_change\")  # execute before function in asynchronously 5 times\r\nmodel = AsyncModel()\r\nmachine = AsyncMachine(model, states=[\"Start\", \"Done\"], transitions=[transition], initial='Start')\r\n\r\nasyncio.get_event_loop().run_until_complete(model.start())\r\n# \u003e\u003e\u003e I am synchronous.\r\n#     I am asynchronous and will block now for 100 milliseconds.\r\n#     I am asynchronous and will block now for 100 milliseconds.\r\n#     I am asynchronous and will block now for 100 milliseconds.\r\n#     I am asynchronous and will block now for 100 milliseconds.\r\n#     I am asynchronous and will block now for 100 milliseconds.\r\n#     I am synchronous and will block the event loop (what I probably shouldn't)\r\n#     I am done waiting synchronously.\r\n#     I am done waiting.\r\n#     I am done waiting.\r\n#     I am done waiting.\r\n#     I am done waiting.\r\n#     I am done waiting.\r\n#     I am synchronous again. Execution took 101 ms.\r\nassert model.is_Done()\r\n```\r\n\r\nSo, why do you need to use Python 3.7 or later you may ask.\r\nAsync support has been introduced earlier.\r\n`AsyncMachine` makes use of `contextvars` to handle running callbacks when new events arrive before a transition\r\nhas been finished:\r\n\r\n```python\r\nasync def await_never_return():\r\n    await asyncio.sleep(100)\r\n    raise ValueError(\"That took too long!\")\r\n\r\nasync def fix():\r\n    await m2.fix()\r\n\r\nm1 = AsyncMachine(states=['A', 'B', 'C'], initial='A', name=\"m1\")\r\nm2 = AsyncMachine(states=['A', 'B', 'C'], initial='A', name=\"m2\")\r\nm2.add_transition(trigger='go', source='A', dest='B', before=await_never_return)\r\nm2.add_transition(trigger='fix', source='A', dest='C')\r\nm1.add_transition(trigger='go', source='A', dest='B', after='go')\r\nm1.add_transition(trigger='go', source='B', dest='C', after=fix)\r\nasyncio.get_event_loop().run_until_complete(asyncio.gather(m2.go(), m1.go()))\r\n\r\nassert m1.state == m2.state\r\n```\r\n\r\nThis example illustrates actually two things:\r\nFirst, that 'go' called in m1's transition from `A` to be `B` is not cancelled and second, calling `m2.fix()` will\r\nhalt the transition attempt of m2 from `A` to `B` by executing 'fix' from `A` to `C`.\r\nThis separation would not be possible without `contextvars`.\r\nNote that `prepare` and `conditions` are NOT treated as ongoing transitions.\r\nThis means that after `conditions` have been evaluated, a transition is executed even though another event already happened.\r\nTasks will only be cancelled when run as a `before` callback or later.\r\n\r\n`AsyncMachine` features a model-special queue mode which can be used when `queued='model'` is passed to the constructor.\r\nWith model-specific queue, events will only be queued when they belong to the same model.\r\nFurthermore, a raised exception will only clear the event queue of the model that raised that exception.\r\nFor the sake of simplicity, let's assume that every event in `asyncion.gather` below is not triggered at the same time but slightly delayed:\r\n\r\n```python\r\nasyncio.gather(model1.event1(), model1.event2(), model2.event1())\r\n# execution order with AsyncMachine(queued=True)\r\n# model1.event1 -\u003e model1.event2 -\u003e model2.event1\r\n# execution order with AsyncMachine(queued='model')\r\n# (model1.event1, model2.event1) -\u003e model1.event2\r\n\r\nasyncio.gather(model1.event1(), model1.error(), model1.event3(), model2.event1(), model2.event2(), model2.event3())\r\n# execution order with AsyncMachine(queued=True)\r\n# model1.event1 -\u003e model1.error\r\n# execution order with AsyncMachine(queued='model')\r\n# (model1.event1, model2.event1) -\u003e (model1.error, model2.event2) -\u003e model2.event3\r\n```\r\n\r\nNote that queue modes must not be changed after machine construction. \r\n\r\n#### \u003ca name=\"state-features\"\u003e\u003c/a\u003eAdding features to states\r\n\r\nIf your superheroes need some custom behaviour, you can throw in some extra functionality by decorating machine states:\r\n\r\n```python\r\nfrom time import sleep\r\nfrom transitions import Machine\r\nfrom transitions.extensions.states import add_state_features, Tags, Timeout\r\n\r\n\r\n@add_state_features(Tags, Timeout)\r\nclass CustomStateMachine(Machine):\r\n    pass\r\n\r\n\r\nclass SocialSuperhero(object):\r\n    def __init__(self):\r\n        self.entourage = 0\r\n\r\n    def on_enter_waiting(self):\r\n        self.entourage += 1\r\n\r\n\r\nstates = [{'name': 'preparing', 'tags': ['home', 'busy']},\r\n          {'name': 'waiting', 'timeout': 1, 'on_timeout': 'go'},\r\n          {'name': 'away'}]  # The city needs us!\r\n\r\ntransitions = [['done', 'preparing', 'waiting'],\r\n               ['join', 'waiting', 'waiting'],  # Entering Waiting again will increase our entourage\r\n               ['go', 'waiting', 'away']]  # Okay, let' move\r\n\r\nhero = SocialSuperhero()\r\nmachine = CustomStateMachine(model=hero, states=states, transitions=transitions, initial='preparing')\r\nassert hero.state == 'preparing'  # Preparing for the night shift\r\nassert machine.get_state(hero.state).is_busy  # We are at home and busy\r\nhero.done()\r\nassert hero.state == 'waiting'  # Waiting for fellow superheroes to join us\r\nassert hero.entourage == 1  # It's just us so far\r\nsleep(0.7)  # Waiting...\r\nhero.join()  # Weeh, we got company\r\nsleep(0.5)  # Waiting...\r\nhero.join()  # Even more company \\o/\r\nsleep(2)  # Waiting...\r\nassert hero.state == 'away'  # Impatient superhero already left the building\r\nassert machine.get_state(hero.state).is_home is False  # Yupp, not at home anymore\r\nassert hero.entourage == 3  # At least he is not alone\r\n```\r\n\r\nCurrently, transitions comes equipped with the following state features:\r\n\r\n* **Timeout** -- triggers an event after some time has passed\r\n    - keyword: `timeout` (int, optional) -- if passed, an entered state will timeout after `timeout` seconds\r\n    - keyword: `on_timeout` (string/callable, optional) -- will be called when timeout time has been reached\r\n    - will raise an `AttributeError` when `timeout` is set but `on_timeout` is not\r\n    - 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.\r\n\r\n* **Tags** -- adds tags to states\r\n    - keyword: `tags` (list, optional) -- assigns tags to a state\r\n    - `State.is_\u003ctag_name\u003e` will return `True` when the state has been tagged with `tag_name`, else `False`\r\n\r\n* **Error** -- raises a `MachineError` when a state cannot be left \r\n    - inherits from `Tags` (if you use `Error` do not use `Tags`)\r\n    - keyword: `accepted` (bool, optional) -- marks a state as accepted\r\n    - alternatively the keyword `tags` can be passed, containing 'accepted'\r\n    - Note: Errors will only be raised if `auto_transitions` has been set to `False`. Otherwise every state can be exited with `to_\u003cstate\u003e` methods.\r\n    \r\n* **Volatile** -- initialises an object every time a state is entered\r\n    - 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\r\n    - keyword: `hook` (string, default='scope') -- The model's attribute name fore the temporal object.\r\n\r\nYou 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.\r\nUsing `@add_state_features` has a drawback which is that decorated machines cannot be pickled (more precisely, the dynamically generated `CustomState` cannot be pickled).\r\nThis might be a reason to write a dedicated custom state class instead.\r\nDepending on the chosen state machine, your custom state class may need to provide certain state features. For instance, `HierarchicalMachine` 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:\r\n\r\n```python\r\nfrom transitions import Machine, State\r\n\r\nclass MyState(State):\r\n    pass\r\n\r\nclass CustomMachine(Machine):\r\n    # Use MyState as state class\r\n    state_cls = MyState\r\n\r\n    \r\nclass VerboseMachine(Machine):\r\n\r\n    # `Machine._create_state` is a class method but we can \r\n    # override it to be an instance method\r\n    def _create_state(self, *args, **kwargs):\r\n        print(\"Creating a new state with machine '{0}'\".format(self.name))\r\n        return MyState(*args, **kwargs)\r\n```\r\n\r\nIf you want to avoid threads in your `AsyncMachine` entirely, you can replace the `Timeout` state feature with `AsyncTimeout` from the `asyncio` extension:\r\n\r\n```python\r\nimport asyncio\r\nfrom transitions.extensions.states import add_state_features\r\nfrom transitions.extensions.asyncio import AsyncTimeout, AsyncMachine\r\n\r\n@add_state_features(AsyncTimeout)\r\nclass TimeoutMachine(AsyncMachine):\r\n    pass\r\n\r\nstates = ['A', {'name': 'B', 'timeout': 0.2, 'on_timeout': 'to_C'}, 'C']\r\nm = TimeoutMachine(states=states, initial='A', queued=True)  # see remark below\r\nasyncio.run(asyncio.wait([m.to_B(), asyncio.sleep(0.1)]))\r\nassert m.is_B()  # timeout shouldn't be triggered\r\nasyncio.run(asyncio.wait([m.to_B(), asyncio.sleep(0.3)]))\r\nassert m.is_C()   # now timeout should have been processed\r\n```\r\n\r\nYou should consider passing `queued=True` to the `TimeoutMachine` constructor. This will make sure that events are processed sequentially and avoid asynchronous [racing conditions](https://github.com/pytransitions/transitions/issues/459) that may appear when timeout and event happen in close proximity.\r\n\r\n#### \u003ca name=\"django-support\"\u003e\u003c/a\u003e Using transitions together with Django\r\n\r\nYou can have a look at the [FAQ](examples/Frequently%20asked%20questions.ipynb) for some inspiration or checkout `django-transitions`.\r\nIt has been developed by Christian Ledermann and is also hosted on [Github](https://github.com/PrimarySite/django-transitions).\r\n[The documentation](https://django-transitions.readthedocs.io/en/latest/) contains some usage examples.\r\n\r\n\r\n### \u003ca name=\"bug-reports\"\u003e\u003c/a\u003eI have a [bug report/issue/question]...\r\n\r\nFirst, congratulations! You reached the end of the documentation!\r\nIf you want to try out `transitions` before you install it, you can do that in an interactive Jupyter notebook at mybinder.org.\r\nJust click this button 👉 [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/pytransitions/transitions/master?filepath=examples%2FPlayground.ipynb).\r\n\r\nFor bug reports and other issues, please [open an issue](https://github.com/pytransitions/transitions) on GitHub.\r\n\r\nFor usage questions, post on Stack Overflow, making sure to tag your question with the [`pytransitions` tag](https://stackoverflow.com/questions/tagged/pytransitions). Do not forget to have a look at the [extended examples](./examples)!\r\n\r\nFor any other questions, solicitations, or large unrestricted monetary gifts, email [Tal Yarkoni](mailto:tyarkoni@gmail.com) (initial author) and/or [Alexander Neumann](mailto:aleneum@gmail.com) (current maintainer).\r\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffaucetsdn%2Fpython3-transitions","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffaucetsdn%2Fpython3-transitions","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffaucetsdn%2Fpython3-transitions/lists"}