How To Define Enum Of Trigger For `transitions` State Machine?
As an unrelated followup to this answer, which isuses the following working code: from transitions import Machine from transitions import EventData from typing import Callable from
Solution 1:
As vish already pointed out, there is no way to use Enums as triggers directly. Transitions binds trigger names as methods to models and thus requires triggers to be strings. However, Machine
and all subclasses have been written with inheritance in mind. If you want to use Enums instead of classes and class attributes, you can just derive a suitable EnumTransitionMachine
and get a unified interface:
from transitions import Machine
from enum import Enum, auto
classState(Enum):
A = auto()
B = auto()
C = auto()
classTransitions(Enum):
GO = auto()
PROCEED = auto()
classEnumTransitionMachine(Machine):
defadd_transition(self, trigger, *args, **kwargs):
super().add_transition(trigger.name.lower() ifhasattr(trigger, 'name') else trigger, *args, **kwargs)
transitions = [[Transitions.GO, State.A, State.B], [Transitions.PROCEED, State.B, State.C]]
m = EnumTransitionMachine(states=State, transitions=transitions, initial=State.A)
m.go()
assert m.state == State.B
m.proceed()
assert m.is_C()
FYI: there is also the possibility to use Enums
with string values:
classState(Enum):
A = "A"
B = "B"
C = "C"classTransitions(Enum):
GO = "GO"
PROCEED = "PROCEED"# you could use the enum's value then instead:defadd_transition(self, trigger, *args, **kwargs):
super().add_transition(trigger.value.lower() ifhasattr(trigger, 'value') else trigger, *args, **kwargs)
Post a Comment for "How To Define Enum Of Trigger For `transitions` State Machine?"