Skip to content

Commit

Permalink
add DynamicState to FAQ (#146)
Browse files Browse the repository at this point in the history
  • Loading branch information
aleneum committed Jun 28, 2021
1 parent e66d02e commit 24d46b4
Showing 1 changed file with 55 additions and 1 deletion.
56 changes: 55 additions & 1 deletion examples/Frequently asked questions.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -301,11 +301,65 @@
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You lose `model.is_<state>` convenience functions and the ability to add callbacks such as `Model.on_enter_<state>` automatically. However, the second limitation can be tackled with dynamic resolution in states as pointed out by [mvanderlee](https://github.com/mvanderlee) [here](https://github.com/pytransitions/transitions/issues/146#issuecomment-869049925):"
]
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"from transitions import State\n",
"import logging\n",
"\n",
"logger = logging.getLogger(__name__)\n",
"\n",
"\n",
"class DynamicState(State):\n",
" \"\"\" Need to dynamically get the on_enter and on_exit callbacks since the\n",
" model can not be registered to the Machine due to Memory limitations\n",
" \"\"\"\n",
"\n",
" def enter(self, event_data):\n",
" \"\"\" Triggered when a state is entered. \"\"\"\n",
" logger.debug(\"%sEntering state %s. Processing callbacks...\", event_data.machine.name, self.name)\n",
" if hasattr(event_data.model, f'on_enter_{self.name}'):\n",
" event_data.machine.callbacks([getattr(event_data.model, f'on_enter_{self.name}')], event_data)\n",
" logger.info(\"%sFinished processing state %s enter callbacks.\", event_data.machine.name, self.name)\n",
"\n",
" def exit(self, event_data):\n",
" \"\"\" Triggered when a state is exited. \"\"\"\n",
" logger.debug(\"%sExiting state %s. Processing callbacks...\", event_data.machine.name, self.name)\n",
" if hasattr(event_data.model, f'on_exit_{self.name}'):\n",
" event_data.machine.callbacks([getattr(event_data.model, f'on_exit_{self.name}')], event_data)\n",
" logger.info(\"%sFinished processing state %s exit callbacks.\", event_data.machine.name, self.name)\n",
"\n",
"\n",
"class DynamicMachine(Machine):\n",
" \"\"\"Required to use DynamicState\"\"\"\n",
" state_cls = DynamicState"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "markdown",
"source": [
"### Is there a 'during' callback which is called when no transition has been successful?\n",
"\n",
"Currently, `transitions` has no such callback. This example from the issue discussed [here](https://github.com/pytransitions/transitions/issues/342) might give you a basic idea about how to extend `Machine` with such a feature:"
]
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%% md\n"
}
}
},
{
"cell_type": "code",
Expand Down

0 comments on commit 24d46b4

Please sign in to comment.