ObserversΒΆ

Observers are a way do generically add behavior to a StateMachine without changing its internal implementation.

One possible use case is to add an observer that prints a log message when the SM runs a transition or enters a new state.

Giving the Traffic light machine as example:

>>> from tests.examples.traffic_light_machine import TrafficLightMachine

>>> class LogObserver(object):
...     def __init__(self, name):
...         self.name = name
...
...     def after_transition(self, event, source, target):
...         print("{} after: {}--({})-->{}".format(self.name, source.id, event, target.id))
...
...     def on_enter_state(self, target, event):
...         print("{} enter: {} from {}".format(self.name, target.id, event))


>>> sm = TrafficLightMachine()

>>> sm.add_observer(LogObserver("Paulista Avenue"))  
TrafficLightMachine...

>>> sm.cycle()
Paulista Avenue enter: yellow from cycle
Paulista Avenue after: green--(cycle)-->yellow
'Running cycle from green to yellow'

Hint

The StateMachine itself is registered as an observer, so by using .add_observer() an external object can have the same level of functionalities provided to the built-in class.

See also

See Actions, Validators and guards for a list of possible callbacks.

And also Dynamic dispatch to know more about how the lib calls methods to match their signature.