Diagrams¶
You can generate diagrams from your statemachine.
Note
This functionality depends on pydot, it means that you need to have pydot installed on your system. pydot is a Python library that allows you to create and manipulate graphs in Graphviz’s dot language.
In order to use pydot, we also need to have Graphviz installed on your system.
You can install this library already with pydot dependency using the extras
install option:
pip install python-statemachine[diagrams]
Or to install pydot
manually, you can use pip by running the following command:
pip install pydot
To install Graphviz, you can visit the Graphviz website and follow the instructions for your operating system. Alternatively, you can use a package manager to install Graphviz. For example, on Debian-based systems (such as Ubuntu), you can use the following command:
apt-get install graphviz
How to generate a diagram at runtime¶
>>> from statemachine.contrib.diagram import DotGraphMachine
>>> from tests.examples.order_control_machine import OrderControl
>>> graph = DotGraphMachine(OrderControl) # also accepts instances
>>> dot = graph()
>>> dot.to_string()
'digraph list {...
With a dot
graph instance, you can also generate images:
>>> dot.write_png("docs/images/order_control_machine_initial.png")
As this one:
The current state is also highlighted:
>>> from statemachine.contrib.diagram import DotGraphMachine
>>> from tests.examples.order_control_machine import OrderControl
>>> machine = OrderControl()
>>> graph = DotGraphMachine(machine) # also accepts instances
>>> machine.receive_payment(10)
[10]
>>> graph().write_png("docs/images/order_control_machine_processing.png")
Generate from the command line¶
You can also generate a diagram from the command line using the statemachine.contrib.diagram
as a module.
❯ python -m statemachine.contrib.diagram --help
usage: diagram.py [OPTION] <classpath> <out>
Generate diagrams for StateMachine classes.
positional arguments:
classpath A fully-qualified dotted path to the StateMachine class.
out File to generate the image using extension as the output format.
optional arguments:
-h, --help show this help message and exit
Example:
python -m statemachine.contrib.diagram tests.examples.traffic_light_machine.TrafficLightMachine m.png
JupyterLab / Jupyter integration¶
Machines instances are automatically displayed as a diagram when used on JupyterLab cells: