0
# Core State Machine
1
2
The core state machine functionality provides the foundation for all state machine operations in the transitions library. The Machine class manages states, transitions, models, and events with extensive configuration options and callback support.
3
4
## Capabilities
5
6
### Machine Class
7
8
The central state machine implementation that manages states, transitions, and models.
9
10
```python { .api }
11
class Machine:
12
def __init__(
13
self,
14
model='self',
15
states=None,
16
initial='initial',
17
transitions=None,
18
send_event=False,
19
auto_transitions=True,
20
ordered_transitions=False,
21
ignore_invalid_triggers=None,
22
before_state_change=None,
23
after_state_change=None,
24
name=None,
25
queued=False,
26
prepare_event=None,
27
finalize_event=None,
28
model_attribute='state',
29
model_override=False,
30
on_exception=None,
31
on_final=None,
32
**kwargs
33
):
34
"""
35
Initialize a state machine.
36
37
Parameters:
38
- model: The object(s) whose states we want to manage. 'self' uses the machine itself.
39
- states: List of state names or State objects
40
- initial: Name of the initial state
41
- transitions: List of transition dictionaries
42
- send_event: When True, arguments are wrapped in EventData
43
- auto_transitions: When True, every state gets to_{state}() convenience methods
44
- ordered_transitions: When True, add ordered transitions between consecutive states
45
- ignore_invalid_triggers: When True, invalid triggers are silently ignored
46
- before_state_change: Callbacks executed before any transition
47
- after_state_change: Callbacks executed after any transition
48
- name: Name of the machine instance for logging
49
- queued: When True, transitions are queued and executed sequentially
50
- prepare_event: Callbacks executed when an event is triggered
51
- finalize_event: Callbacks executed after all transition callbacks
52
- model_attribute: Name of the model attribute that stores the state
53
- model_override: When True, override model methods with trigger methods
54
- on_exception: Callbacks executed when Event raises an exception
55
- on_final: Callbacks executed when a final state is reached
56
"""
57
```
58
59
### State Management
60
61
Methods for managing states in the machine.
62
63
```python { .api }
64
def add_state(self, states, on_enter=None, on_exit=None, ignore_invalid_triggers=None, **kwargs):
65
"""
66
Add new state(s) to the machine.
67
68
Parameters:
69
- states: State name, State object, or list of either
70
- on_enter: Callbacks triggered when state is entered
71
- on_exit: Callbacks triggered when state is exited
72
- ignore_invalid_triggers: Override machine's ignore_invalid_triggers setting
73
"""
74
75
def add_states(self, states, on_enter=None, on_exit=None, ignore_invalid_triggers=None, **kwargs):
76
"""Alias for add_state that handles multiple states."""
77
78
def get_state(self, state):
79
"""
80
Return the State instance with the passed name.
81
82
Parameters:
83
- state: Name of the state to retrieve
84
85
Returns:
86
State object
87
"""
88
89
def is_state(self, state, model):
90
"""
91
Check whether the current state matches the named state.
92
93
Parameters:
94
- state: Name of the state to check
95
- model: Model to check state for
96
97
Returns:
98
bool: True if current state matches
99
"""
100
101
def get_model_state(self, model):
102
"""
103
Get the state of a specific model.
104
105
Parameters:
106
- model: Model to get state for
107
108
Returns:
109
Current state of the model
110
"""
111
112
def set_state(self, state, model=None):
113
"""
114
Set the current state.
115
116
Parameters:
117
- state: Name of the state to set
118
- model: Model to set state for (all models if None)
119
"""
120
```
121
122
### Transition Management
123
124
Methods for managing transitions between states.
125
126
```python { .api }
127
def add_transition(
128
self,
129
trigger,
130
source,
131
dest,
132
conditions=None,
133
unless=None,
134
before=None,
135
after=None,
136
prepare=None,
137
**kwargs
138
):
139
"""
140
Create a new transition.
141
142
Parameters:
143
- trigger: Name of the triggering method
144
- source: Source state name or list of source states
145
- dest: Destination state name
146
- conditions: Callbacks that must return True for transition to execute
147
- unless: Callbacks that must return False for transition to execute
148
- before: Callbacks executed before the transition
149
- after: Callbacks executed after the transition
150
- prepare: Callbacks executed before condition checks
151
"""
152
153
def add_transitions(self, transitions):
154
"""
155
Add several transitions at once.
156
157
Parameters:
158
- transitions: List of transition dictionaries
159
"""
160
161
def add_ordered_transitions(
162
self,
163
states=None,
164
trigger='next_state',
165
loop=True,
166
loop_includes_initial=True,
167
conditions=None,
168
unless=None,
169
before=None,
170
after=None,
171
prepare=None,
172
**kwargs
173
):
174
"""
175
Add transitions that move linearly from state to state.
176
177
Parameters:
178
- states: List of state names (uses machine states if None)
179
- trigger: Name of the trigger method
180
- loop: Whether to loop back to first state from last state
181
- loop_includes_initial: Whether the loop includes the initial state
182
- conditions: Conditions for all transitions
183
- unless: Unless conditions for all transitions
184
- before: Before callbacks for all transitions
185
- after: After callbacks for all transitions
186
- prepare: Prepare callbacks for all transitions
187
"""
188
189
def get_transitions(self, trigger="", source="*", dest="*"):
190
"""
191
Return transitions matching the criteria.
192
193
Parameters:
194
- trigger: Trigger name to filter by (empty string for all)
195
- source: Source state to filter by ("*" for all)
196
- dest: Destination state to filter by ("*" for all)
197
198
Returns:
199
List of matching Transition objects
200
"""
201
202
def remove_transition(self, trigger, source="*", dest="*"):
203
"""
204
Remove transitions matching the criteria.
205
206
Parameters:
207
- trigger: Trigger name
208
- source: Source state ("*" for all)
209
- dest: Destination state ("*" for all)
210
"""
211
```
212
213
### Model Management
214
215
Methods for managing models attached to the machine.
216
217
```python { .api }
218
def add_model(self, model, initial=None):
219
"""
220
Register a model with the state machine.
221
222
Parameters:
223
- model: Model object to register
224
- initial: Initial state for this model (uses machine initial if None)
225
"""
226
227
def remove_model(self, model):
228
"""
229
Remove a model from the state machine.
230
231
Parameters:
232
- model: Model object to remove
233
"""
234
```
235
236
### Event Handling
237
238
Methods for triggering events and managing callbacks.
239
240
```python { .api }
241
def dispatch(self, trigger, *args, **kwargs):
242
"""
243
Trigger an event on all models assigned to the machine.
244
245
Parameters:
246
- trigger: Name of the trigger method
247
- args: Positional arguments passed to callbacks
248
- kwargs: Keyword arguments passed to callbacks
249
250
Returns:
251
bool: True if at least one transition was successful
252
"""
253
254
def get_triggers(self, *args):
255
"""
256
Collect all triggers available from certain states.
257
258
Parameters:
259
- args: State names to get triggers for (all states if empty)
260
261
Returns:
262
List of trigger names
263
"""
264
```
265
266
### Utility Methods
267
268
Helper methods for callback handling and state management.
269
270
```python { .api }
271
def callbacks(self, funcs, event_data):
272
"""
273
Trigger a list of callbacks with event data.
274
275
Parameters:
276
- funcs: List of callback functions
277
- event_data: EventData object to pass to callbacks
278
"""
279
280
def callback(self, func, event_data):
281
"""
282
Trigger a single callback function.
283
284
Parameters:
285
- func: Callback function or method name
286
- event_data: EventData object to pass to callback
287
"""
288
289
def resolve_callable(self, func, event_data):
290
"""
291
Convert a model's property/method name or path to callable.
292
293
Parameters:
294
- func: Function, method name, or dotted path
295
- event_data: EventData object for context
296
297
Returns:
298
Callable function
299
"""
300
```
301
302
### Properties
303
304
Machine properties for state and configuration access.
305
306
```python { .api }
307
@property
308
def initial(self):
309
"""Get or set the initial state name."""
310
311
@property
312
def has_queue(self):
313
"""Return boolean indicating if machine has queue enabled."""
314
315
@property
316
def model(self):
317
"""List of models attached to the machine."""
318
319
@property
320
def before_state_change(self):
321
"""Callbacks executed before any state transition."""
322
323
@property
324
def after_state_change(self):
325
"""Callbacks executed after any state transition."""
326
327
@property
328
def prepare_event(self):
329
"""Callbacks executed when an event is triggered."""
330
331
@property
332
def finalize_event(self):
333
"""Callbacks executed after all transition callbacks."""
334
335
@property
336
def on_exception(self):
337
"""Callbacks executed when an Event raises an exception."""
338
339
@property
340
def on_final(self):
341
"""Callbacks executed when a final state is reached."""
342
```
343
344
## Utility Functions
345
346
### listify Function
347
348
```python { .api }
349
def listify(obj):
350
"""
351
Wrap a passed object into a list if it's not already a list or tuple.
352
353
Parameters:
354
- obj: Object to convert to list (returns empty list if None)
355
356
Returns:
357
list: List containing the object, or empty list if obj is None
358
"""
359
```
360
361
## Exception Classes
362
363
### MachineError
364
365
```python { .api }
366
class MachineError(Exception):
367
"""
368
Exception used for issues related to state transitions and current states.
369
370
Parameters:
371
- value: Error message or description
372
"""
373
def __init__(self, value): ...
374
```
375
376
## Usage Examples
377
378
### Basic State Machine Setup
379
380
```python
381
from transitions import Machine
382
383
# Define a simple model
384
class TrafficLight:
385
pass
386
387
# Define states and transitions
388
states = ['red', 'yellow', 'green']
389
transitions = [
390
{'trigger': 'go', 'source': 'red', 'dest': 'green'},
391
{'trigger': 'slow_down', 'source': 'green', 'dest': 'yellow'},
392
{'trigger': 'stop', 'source': 'yellow', 'dest': 'red'}
393
]
394
395
# Create the machine
396
light = TrafficLight()
397
machine = Machine(model=light, states=states, transitions=transitions, initial='red')
398
399
# Use the state machine
400
print(light.state) # 'red'
401
light.go()
402
print(light.state) # 'green'
403
```
404
405
### Using Callbacks
406
407
```python
408
from transitions import Machine
409
410
class Robot:
411
def __init__(self):
412
self.battery = 100
413
414
def check_battery(self):
415
print(f"Battery level: {self.battery}%")
416
return self.battery > 20
417
418
def consume_battery(self):
419
self.battery -= 10
420
print(f"Battery consumed, remaining: {self.battery}%")
421
422
states = ['idle', 'working', 'charging']
423
transitions = [
424
{
425
'trigger': 'start_work',
426
'source': 'idle',
427
'dest': 'working',
428
'conditions': 'check_battery',
429
'after': 'consume_battery'
430
},
431
{'trigger': 'finish_work', 'source': 'working', 'dest': 'idle'},
432
{'trigger': 'charge', 'source': ['idle', 'working'], 'dest': 'charging'}
433
]
434
435
robot = Robot()
436
machine = Machine(model=robot, states=states, transitions=transitions, initial='idle')
437
438
robot.start_work() # Checks battery and consumes it
439
```