CKTIS / Python
Finite-state machines
The current state and event form a key that selects the next state in a finite transition table.
Version: Python 3.14; repository image, production runtime not attested
Syntax
state = transitions[state, event]The current state and event form a key that selects the next state in a finite transition table.
A transition function separates the rules from the event loop. Missing pairs need an explicit policy. Here get uses None as a sentinel because no valid state has that value.
A second open in the open state is rejected without changing state. The following close ends in closed.
edges={('idle','start'):'active',('active','stop'):'idle'}
def step(state,event):
return edges[(state,event)]
assert step(step('idle','start'),'stop')=='idle'
try: step('idle','stop')
except KeyError: pass
else: raise AssertionError
Examples
transitions = {
("closed", "open"): "open",
("open", "close"): "closed",
}
state = "closed"
for event in ["open", "open", "close"]:
target = transitions.get((state, event))
if target is None:
print("rejected", state, event)
else:
state = target
print(state)
Result
rejected open open closed
A second open in the open state is rejected without changing state. The following close ends in closed.